Author

Topic: Python code for private key --> address (Read 3992 times)

legendary
Activity: 1428
Merit: 1093
Core Armory Developer
August 28, 2012, 01:05:02 PM
#3
The old PyBtcEngine project (the precursor to Armory), had a pure-python implementation of all the ECDSA math.  Granted, that was based on an old post by Russian forum user "Lis", in which he released the pure-python-ECDSA code to public domain.  I just wrapped it up.

If you clone the PyBtcEngine project, you will probably only need to to "from pybtcengine import *" and then run the relevant calls.  Here's some sample code that showing how to convert private key to address in the first four lines (in bold).  Then it does a ton more.  This is in unittest.py, where I created a private key ('aa'*32) and an empty transaction and tested signing then verifying it.  


Quote
print 'Testing PyCreateAndSignTx'
AddrA = PyBtcAddress().createFromPrivateKey(hex_to_int('aa'*32))
AddrB = PyBtcAddress().createFromPrivateKey(hex_to_int('bb'*32))
print '   Address A:', AddrA.getAddrStr()
print '   Address B:', AddrB.getAddrStr()


# This TxIn will be completely ignored, so it can contain garbage
txinA = PyTxIn()
txinA.outpoint  = PyOutPoint().unserialize(hex_to_binary('00'*36))
txinA.binScript = hex_to_binary('99'*4)
txinA.sequence  = hex_to_binary('ff'*4)

txoutA = PyTxOut()
txoutA.value = 50 * (10**8 )
txoutA.binScript = '\x76\xa9\x14' + AddrA.getAddr160() + '\x88\xac'

tx1 = PyTx()
tx1.version    = 1
tx1.numInputs  = 1
tx1.inputs     = [txinA]
tx1.numOutputs = 1
tx1.outputs    = [txoutA]
tx1.locktime   = 0

tx1hash = tx1.getHash()
print 'Creating transaction to send coins from A to B'
tx2 = PyCreateAndSignTx( [[ AddrA, tx1, 0 ]],  [[AddrB, 50*(10**8 )]])

print 'Verifying the transaction we just created',
psp = PyScriptProcessor()
psp.setTxObjects(tx1, tx2, 0)
verifResult = psp.verifyTransactionValid()


More than you asked for... but maybe you'll be interested in all of it later Smiley

Btw, Armory has the same functionality, but I outsourced all the crypto to C++, where it's a hell of a lot faster.  If you want to use the latest, you can do that, but it will require compiling... but the crypto itself hasn't really changed.
sr. member
Activity: 476
Merit: 250
August 28, 2012, 12:37:38 PM
#2
Check electrum code. Everything's there.
legendary
Activity: 1792
Merit: 1111
August 28, 2012, 12:09:03 PM
#1
Is there any Python code that translates private key (in HEX format) to an bitcoin address? Thanks!
Jump to: