从私钥生成比特币公共地址的尝试失败

猕猴桃

我有一个程序可以从随机生成的私钥生成比特币公共地址。但是,当我在 blockchain.info 上测试公共地址的有效性时,它告诉我该地址无效。我在代码中哪里出错了?

//modules
const secureRandom = require("secure-random");
const elliptic = require("elliptic");
const ecdsa = new elliptic.ec('secp256k1');
const sha256 = require('js-sha256');
const ripemd160 = require('ripemd160');
const base58 = require('bs58');
//variable that caps the address possiblities due to elliptic curve limitations
const max = Buffer.from("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140","hex");
//generates a key that does not exceed 'max'
  function createWalletAddress(){
      var foundPrivateKey = false;
      var privateKey;
      while(!foundPrivateKey){
        privateKey=secureRandom.randomBuffer(32);
        if(Buffer.compare(max,privateKey)){
          foundPrivateKey=true
        }
      }
      //prints the private key generated
      console.log("Private: " +privateKey.toString("hex"))
      //turns private key into public and prints it
      var keys = ecdsa.keyFromPrivate(privateKey);
      var publicKey = keys.getPublic("hex");
      console.log("Public: "+publicKey);
      //getting the public key hash
      const hashBeforePKH = sha256(Buffer.from(publicKey, "hex"));
      const publicKeyHash = new ripemd160().update(Buffer.from(hashBeforePKH,"hex")).digest();
      console.log("PKH "+publicKeyHash.toString("hex"));
      return publicKeyHash;
  }

  function createPublicAddress(publicKeyHash){
      const addPrefix="00"+publicKeyHash.toString('hex');
      const hashAddress=sha256(addPrefix);
      const hashAgain = sha256(Buffer.from(hashAddress,"hex"));
      const checkSum = hashAgain.substring(0,8);
      const combine = addPrefix.toString("hex")+checkSum;
      const address= base58.encode(Buffer.from(combine,"hex"));
       console.log("address " + address);
  }

巴丘克

校验和计算错误,应该是 0xf38580e3

尝试散列一个缓冲区而不是字符串:

function createPublicAddress(publicKeyHash){
  const addPrefix="00"+publicKeyHash.toString('hex');
  const hashAddress=sha256(Buffer.from(addPrefix, 'hex'));
  ...
}

您也可以使用类似的方法bs58check而不是手动计算校验和。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章