2

我正在学习区块链并想创建一个创建地址的示例,纯粹用于教育目的 - 不会在任何接近生产的地方完成。

任务:创建160个随机位,将其转换为十六进制,将其转换为基数58,然后通过反转过程来测试正确性。

它有点工作,但是在二进制之前和之后的比较中我得到间歇性的“错误”。hexStringToBinary 函数返回不同长度的字符串:

const bs58 = require('bs58');

//20 * 8 = 160
function generate20Bytes () {
  let byteArray = [];
  let bytes = 0;
  while (bytes < 20) {
    let byte = '';
    while (byte.length < 8) {
      byte += Math.floor(Math.random() * 2);
    }
    byteArray.push(byte);
    bytes++;
  }
  return byteArray;
}

//the issue is probably from here
function hexStringToBinary (string) {
  return string.match(/.{1,2}/g)
    .map(hex => parseInt(hex, 16).toString(2).padStart(8, '0'));
}

const addressArray = generate20Bytes();
const binaryAddress = addressArray.join('');
const hex = addressArray.map(byte => parseInt(byte, 2).toString(16)).join('');
console.log(hex);

// then lets convert it to base 58
const base58 = bs58.encode(Buffer.from(hex));
console.log('base 58');
console.log(base58);

// lets see if we can reverse the process
const destructuredHex = bs58.decode(base58).toString();
console.log('hex is the same');
console.log(hex === destructuredHex);

// lets convert back to a binary string
const destructuredAddress = hexStringToBinary(destructuredHex).join('');
console.log('destructured address');
console.log(destructuredAddress);
console.log('binaryAddress address');
console.log(binaryAddress);

//intermittent false/true
console.log(destructuredAddress === binaryAddress);
4

1 回答 1

0

开始使用 tdd 进行重构。意识到它不是零填充十六进制< 16。我的游乐场回购

于 2018-05-10T23:06:22.687 回答