如何将scriptPubKey字节转换为比特币地址

问题描述 投票:1回答:1

我目前正在尝试使用pyblockchain解析区块链。我的问题是我无法正确编码scriptPubKey-尽管我不知道自己可能做错了什么。

下面您可以看到我如何遍历区块链:

from blockchain.reader import BlockchainFileReader

import hashlib
import base58

block_reader = BlockchainFileReader('/media/Data/btc/blocks/blk00325.dat')

count = 0

for block in block_reader:    
    count +=1        
    for t in block.transactions:
        for outp in t.outputs:
            addr = base58.b58encode(outp.script_pub_key)
            if addr.startswith('1'):
                print(addr)        
    if count >= 5:
        break

如果我在Jupyter笔记本中查看outp,我会找到

outp.script_pub_key
>> b'v\xa9\x14\x1e\xbev\x83\xceJd\xad\xc9\x17\xe9\xb1\x93\x7f\x12&Q\xcb\xab\xa1\x88\xac'

此:

base58.b58encode(outp.script_pub_key)
>> 'pkJBVCg6k54E7ZiP7cvxbCvtN9aY9zEcgK'

这不是valid bitcoin address

显然,应该在Base58Check中对比特币地址进行编码-但是,这也不起作用:

base58.b58encode_check(outp.script_pub_key)
>> '6PSJQapdQn8VeG9SBuZdH8q2ysyP4ND6dmspzLZb'

所以我在这里做错了什么?

python bitcoin
1个回答
0
投票

对于C ++,有bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet)直接在这里的代码中https://github.com/bitcoin/bitcoin/blob/0cda5573405d75d695aba417e8f22f1301ded001/src/script/standard.cpp#L156

因此,解决方案看起来非常简单

const CScript & scriptPublicKey = block.vtx[ i ]->vout[ j ].scriptPubKey ;
CTxDestination destination ;
std::string address = "unknown" ;
if ( ExtractDestination( scriptPublicKey, destination ) )
    address = CBitcoinAddress( destination ).ToString() ;

关于Python。我敢打赌,问题是首先将ExtractDestination逻辑转换为Python的语言

© www.soinside.com 2019 - 2024. All rights reserved.