blockchain - How can I search blocks for transactions in which an address was used as output without knowing complete address?

blockchain – How can I search blocks for transactions in which an address was used as output without knowing complete address?

 

This C# code scans blocks for transactions and returns the block number and transaction id based on user input.

Requirements:
NBitcoin
Bitcoin Core

using NBitcoin;
using NBitcoin.RPC;

class Scanblocks
{

    const string Cookie = "<path for bitcoin core auth cookie file>";

    static RPCClient InitRpc()
    {
        var creds = RPCCredentialString.Parse(File.ReadAllText(Cookie));
        var rpc = new RPCClient(credentials, Network.TestNet);

        return rpc;
    }

    public static void Main(string[] args)
    {
        Console.WriteLine("Start block:");
        int start_block = Convert.ToInt32(Console.ReadLine());

        Console.WriteLine("End block:");
        int end_block = Convert.ToInt32(Console.ReadLine());

        Console.WriteLine("First few chars of bitcoin address:");
        string address_start = Console.ReadLine();

        Console.WriteLine("Last few chars of bitcoin address:");
        string address_end = Console.ReadLine();

        for (int i = start_block; i <= end_block; i++)
        {
            var rpc = InitRpc();
            var blk = rpc.GetBlock(i);


            foreach (var tx in blk.Transactions)
            {
                foreach (var vout in tx.Outputs)
                {
                    var address_out = vout.ScriptPubKey.GetDestinationAddress(Network.TestNet);
                    
                    if (address_out is not null && address_out.ToString().StartsWith(address_start) && address_out.ToString().EndsWith(address_end))
                    {
                        Console.WriteLine($"n{i}:{tx.GetHash()}");                        
                    }                                      
                   
                }
            }
        }
        
    }
}

Example output for a signet address:

Start block:
1
End block:
2500
First few chars of bitcoin address:
tb1ql5y
Last few chars of bitcoin address:
emazs

2:1248e5f56dd2959429d8ca1117802c0bf59c3deb88abbcafcf17205950ef8fb3

Bitcoin address was tb1ql5yc896q7rstflrdtcjj0eqz925m3806aemazs and used in the txid returned as output.



Source link

Leave a Comment

Your email address will not be published.