NBitcoin 生成重复的比特币地址,对应于等于 1 和 256 的私钥,并且

问题描述

我正在使用 NBitcoin Nuget 开发一个解决方案,突然我发现它为一些等于 1 和 256 的私钥生成了重复的地址,并且...... 我用于生成比特币地址的代码如下:

_bitcoin_address=_private_key.PubKey.GetAddress(ScriptPubKeyType.Legacy,Network.Main).ToString();

当 _private_key=1 或 _private_key=512 相同的地址,例如1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH生成,_private_key=4或_private_key=256时出现同样问题。

这是一个错误还是我犯了一个错误

您可以使用以下代码作为 POC:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
using NBitcoin;

namespace Bitcoin_address_generation
{
    class Program
    {
        static void Main(string[] args)
        {
            //generating a private key that is equal to 1
            byte[] _priv_bytes1 = IntegerToBytes(1,32);

            Key _private_key1 = new Key();
            _private_key1.FromBytes(_priv_bytes1);


            //generating a private key that is equal to 256
            byte[] _priv_bytes256 = IntegerToBytes(256,32);

            Key _private_key256 = new Key();
            _private_key256.FromBytes(_priv_bytes1);

            Console.WriteLine(_private_key1.PubKey.GetAddress(ScriptPubKeyType.Legacy,Network.Main).ToString());

            Console.WriteLine(_private_key256.PubKey.GetAddress(ScriptPubKeyType.Legacy,Network.Main).ToString());
            Console.ReadKey();

        }

        /// <summary>
        /// convert a big integer to byte array
        /// </summary>
        /// <param name="s"></param>
        /// <param name="qLength"></param>
        /// <returns></returns>
        public static byte[] IntegerToBytes(BigInteger s,int qLength)
        {
            byte[] bytes = s.ToByteArray();

            if (qLength < bytes.Length)
            {
                byte[] tmp = new byte[qLength];

                Array.copy(bytes,bytes.Length - tmp.Length,tmp,tmp.Length);

                return tmp;
            }

            if (qLength > bytes.Length)
            {
                byte[] tmp = new byte[qLength];

                Array.copy(bytes,tmp.Length - bytes.Length,bytes.Length);

                return tmp;
            }

            return bytes;
        }
    }
}

解决方法

经过一些问题/答案后,我发现 NBitcoin 没有任何错误,但以下功能有问题:

delay 0.5

修正后的函数必须如下:

public static byte[] IntegerToBytes(BigInteger s,int qLength)
{
    byte[] bytes = s.ToByteArray();

    if (qLength < bytes.Length)
    {
        byte[] tmp = new byte[qLength];

        Array.Copy(bytes,bytes.Length - tmp.Length,tmp,tmp.Length);

        return tmp;
    }

    if (qLength > bytes.Length)
    {
        byte[] tmp = new byte[qLength];

        Array.Copy(bytes,tmp.Length - bytes.Length,bytes.Length);

        return tmp;
    }

    return bytes;
}

最后感谢 Lucas OntiveroDan Gershony,他们帮助我找到并解决了问题。