def getinfo(args): for filename in args: print "----------------" print "Filename: ", filename privateKey = readPrivateKey(filename) k = Key() k.setPrivateKey(privateKey) print "Public key: ", k.getPublicKey().encode("hex") print "Address: ", getAddress(k)
def sendToMultiSigPubKey(bitcoind, amount, toPubKey1, toPubKey2, changeHash, fee): """ Make a transaction to send funds from ourself to a 2-of-2 multi-signature scriptPubKey. The transaction is returned, and is NOT published on the Bitcoin network by this function. Arguments: bitcoind: Bitcoind; the bitcoin daemon from which to retrieve this information amount: int; the amount to be sent, not including the fee (in Satoshi) toPubKey1: str; the first public key toPubKey2: str; the second public key changeHash: str; the SHA256- and RIPEMD160-hashed public key to which any change should be sent (equivalent to the bitcoin address) fee: int; the transaction fee (in Satoshi) Return value: Transaction; the transaction that sends funds as specified. Exceptions: Exception: insufficient funds """ totalIn, inputs = getInputsForAmount(bitcoind, amount+fee) change = totalIn - fee - amount #print "%d -> %d, %d, %d" % (totalIn, amount, change, fee) tx = Transaction( tx_in = [ TxIn(x[0], x[1]) for x in inputs ], tx_out = [ TxOut(amount, Script.multiSigPubKey([toPubKey1, toPubKey2])), TxOut(change, Script.standardPubKey(changeHash)) ] ) for i in range(len(inputs)): scriptPubKey = Script.deserialize(inputs[i][2]) key = Key() key.setPrivateKey(inputs[i][3]) tx.signInput(i, scriptPubKey, [None, key.getPublicKey()], [key]) return tx
def sendToDataPubKey(bitcoind, data, changeHash, fee): """ Make a transaction to publish data on the block chain with an OP_RETURN output. No funds are sent to the OP_RETURN output: everything goes to fee and to the change address. The transaction is returned, and is NOT published on the Bitcoin network by this function. Arguments: bitcoind: Bitcoind; the bitcoin daemon from which to retrieve this information data: str; the data to be included in the scriptPubKey (max. 40 bytes) changeHash: str; the SHA256- and RIPEMD160-hashed public key to which any change should be sent (equivalent to the bitcoin address) fee: int; the transaction fee (in Satoshi) Return value: Transaction; the transaction that sends funds as specified. Exceptions: Exception: insufficient funds """ totalIn, inputs = getInputsForAmount(bitcoind, fee) change = totalIn - fee print "%d -> %d, %d" % (totalIn, change, fee) tx = Transaction( tx_in = [ TxIn(x[0], x[1]) for x in inputs ], tx_out = [ TxOut(0, Script.dataPubKey(data)), TxOut(change, Script.standardPubKey(changeHash)) ] ) for i in range(len(inputs)): scriptPubKey = Script.deserialize(inputs[i][2]) key = Key() key.setPrivateKey(inputs[i][3]) tx.signInput(i, scriptPubKey, [None, key.getPublicKey()], [key]) return tx
def sendToMultiSigPubKey(bitcoind, amount, toPubKey1, toPubKey2, changeHash, fee): """ Make a transaction to send funds from ourself to a 2-of-2 multi-signature scriptPubKey. The transaction is returned, and is NOT published on the Bitcoin network by this function. Arguments: bitcoind: Bitcoind; the bitcoin daemon from which to retrieve this information amount: int; the amount to be sent, not including the fee (in Satoshi) toPubKey1: str; the first public key toPubKey2: str; the second public key changeHash: str; the SHA256- and RIPEMD160-hashed public key to which any change should be sent (equivalent to the bitcoin address) fee: int; the transaction fee (in Satoshi) Return value: Transaction; the transaction that sends funds as specified. Exceptions: Exception: insufficient funds """ totalIn, inputs = getInputsForAmount(bitcoind, amount + fee) change = totalIn - fee - amount #print "%d -> %d, %d, %d" % (totalIn, amount, change, fee) tx = Transaction(tx_in=[TxIn(x[0], x[1]) for x in inputs], tx_out=[ TxOut(amount, Script.multiSigPubKey([toPubKey1, toPubKey2])), TxOut(change, Script.standardPubKey(changeHash)) ]) for i in range(len(inputs)): scriptPubKey = Script.deserialize(inputs[i][2]) key = Key() key.setPrivateKey(inputs[i][3]) tx.signInput(i, scriptPubKey, [None, key.getPublicKey()], [key]) return tx
def sendToDataPubKey(bitcoind, data, changeHash, fee): """ Make a transaction to publish data on the block chain with an OP_RETURN output. No funds are sent to the OP_RETURN output: everything goes to fee and to the change address. The transaction is returned, and is NOT published on the Bitcoin network by this function. Arguments: bitcoind: Bitcoind; the bitcoin daemon from which to retrieve this information data: str; the data to be included in the scriptPubKey (max. 40 bytes) changeHash: str; the SHA256- and RIPEMD160-hashed public key to which any change should be sent (equivalent to the bitcoin address) fee: int; the transaction fee (in Satoshi) Return value: Transaction; the transaction that sends funds as specified. Exceptions: Exception: insufficient funds """ totalIn, inputs = getInputsForAmount(bitcoind, fee) change = totalIn - fee print "%d -> %d, %d" % (totalIn, change, fee) tx = Transaction(tx_in=[TxIn(x[0], x[1]) for x in inputs], tx_out=[ TxOut(0, Script.dataPubKey(data)), TxOut(change, Script.standardPubKey(changeHash)) ]) for i in range(len(inputs)): scriptPubKey = Script.deserialize(inputs[i][2]) key = Key() key.setPrivateKey(inputs[i][3]) tx.signInput(i, scriptPubKey, [None, key.getPublicKey()], [key]) return tx
def __init__(self, inputs: list, outputs: list, key: Key): """ This is a object that represents a transaction that will be loaded into a blockchain TODO: * Cryptographically authenticate this based on a private key. * Encode and store this as raw bytes * A transaction needs to have multiple inputs and outputs :param inputs: a list of all transactions used as an inputs :param outputs: a dict of {destinations: amount} pairs that corrispond to the destinations :param proof: the cryptographic evedence that the sender is the one who created the transaction. :param amount: the amount of currency being sent to the receivers wallet. """ self["uuid"] = sha256().hash(str( time_ns().encode('utf-8'))).hexdigest() self["public_key"] = key.public_key().public_bytes() self["inputs"] = self.tx_inputs(inputs) self["outputs"] = self.tx_outputs(outputs)
d = bitcoind.Bitcoind(s) #(these addresses are mine - thanks for donating :-P) keyHash1 = binascii.unhexlify("fd5627c5eff58991dec54877272e82f758ea8b65") keyHash2 = binascii.unhexlify("ab22c699d3e72f2c1e4896508bf9d8d7910104d0") address1 = base58.encodeBase58Check(keyHash1, 0) address2 = base58.encodeBase58Check(keyHash2, 0) print address1 print address2 #Note: this will fail, unless you change toe above addresses to some of your own privKey1 = base58.decodeBase58Check(d.getPrivateKey(address1), 128) privKey2 = base58.decodeBase58Check(d.getPrivateKey(address2), 128) key1 = Key() key1.setPrivateKey(privKey1) key2 = Key() key2.setPrivateKey(privKey2) print key1.getPublicKey().encode("hex") print key2.getPublicKey().encode("hex") amount = int(100000 * float(raw_input("Amount to be transferred (mBTC): "))) fee = 10000 #0.1 mBTC outputHash = binascii.unhexlify(raw_input("Input hash (empty: create multisig): "))[::-1] if outputHash == "": tx = sendToMultiSigPubKey(d, amount,
def sign(self, key: Key) -> bytes: """ TODO: Implement signing the transaction with the private key to generate a signature """ self["signature"] = key.sign(self["uuid"].encode('utf-8'))
from crypto import Key, SHA256, RIPEMD160 import base58 def readPrivateKey(filename): with open(filename, "rb") as f: privateKey = f.read() privateKey = privateKey.split("\n")[0] #first line privateKey = privateKey.strip() #ignore whitespace return base58.decodeBase58Check(privateKey, 128) #PRIVKEY = 128 def getTraditionalAddress(key): publicKeyHash = RIPEMD160(SHA256(key.getPublicKey())) return base58.encodeBase58Check(publicKeyHash, 0) #PUBKEY_ADDRESS = 0 # get traditional address using a public key (given a private key) privateKey = readPrivateKey('key.txt') k = Key() k.setPrivateKey(privateKey) trad_address = getTraditionalAddress(k) print "Public key: ", k.getPublicKey().encode("hex") print "Public Key Hash " + RIPEMD160(SHA256(k.getPublicKey())).encode("hex") print "Traditional Address: ", trad_address
def spend(args): #Load the keys keys = [] for filename in args: privateKey = readPrivateKey(filename) k = Key() k.setPrivateKey(privateKey) keys.append(k) def getKey(question): for i in range(len(keys)): print i + 1, getAddress(keys[i]) i = int(raw_input(question)) - 1 return keys[i] #Ask for input information: inputs = [] amounts = [] while True: txid = raw_input("Transaction ID of unspent output (Enter to stop): ") txid = txid.strip() if txid == "": break txid = binascii.unhexlify(txid)[::-1] vout = int(raw_input("Output index of unspent output: ")) k = getKey("Address of unspent output: ") inputs.append((txid, vout, k)) amounts.append( int( decimal.Decimal(raw_input("Amount in unspent output (BCC): ")) * BCC)) totalAmount = sum(amounts) print "Total of amounts: %s BCC" % str(decimal.Decimal(totalAmount) / BCC) fee = int(decimal.Decimal(raw_input("Transaction fee (BCC): ")) * BCC) destAddress = raw_input("Destination address: ") destHash = base58.decodeBase58Check(destAddress, 0) #PUBKEY_ADDRESS = 0 destAmount = totalAmount - fee print "Amount sent to destination: %s BCC" % str( decimal.Decimal(destAmount) / BCC) if destAmount < 0: print "Negative amount is not allowed" sys.exit(2) ''' if destAmount > totalAmount - fee: print "Not enough funds" sys.exit(1) ''' tx = btx.Transaction( tx_in=[btx.TxIn(x[0], x[1]) for x in inputs], tx_out=[btx.TxOut(destAmount, btx.Script.standardPubKey(destHash))]) ''' changeKey = getKey("Address to send change amount to: ") changeAddress = getAddress(changeKey) changeHash = base58.decodeBase58Check(changeAddress, 0) #PUBKEY_ADDRESS = 0 changeAmount = totalAmount - destAmount - fee if changeAmount < 0: raise Exception("Error: got negative change amount") elif changeAmount == 0: print "Note: change amount is zero - no change is sent" else: tx.tx_out.append( btx.TxOut(changeAmount, btx.Script.standardPubKey(changeHash)) ) ''' for i in range(len(inputs)): #print tx.tx_in[i].previousOutputHash.encode("hex"), tx.tx_in[i].previousOutputIndex key = inputs[i][2] address = getAddress(key) hash = base58.decodeBase58Check(address, 0) #PUBKEY_ADDRESS = 0 scriptPubKey = btx.Script.standardPubKey(hash) tx.signInput(i, scriptPubKey, [None, key.getPublicKey()], [key], amounts[i]) print "Serialized transaction:" print tx.serialize().encode("hex") print "Transaction ID:", tx.getTransactionID()[::-1].encode("hex")
def decode(args): s = args[0] amounts = [int(decimal.Decimal(a) * BCC) for a in args[1:]] serialized = binascii.unhexlify(s) tx = btx.Transaction.deserialize(serialized) print 'lockTime: ', tx.lockTime for i in range(len(tx.tx_in)): tx_in = tx.tx_in[i] print 'TxIn:' print ' amount: %s BCC' % str(decimal.Decimal(amounts[i]) / BCC) print ' prevOutputHash: ', tx_in.previousOutputHash.encode("hex") print ' prevOutputIndex: ', tx_in.previousOutputIndex print ' sequenceNumber: 0x%08x' % tx_in.sequenceNumber print ' script:' for e in tx_in.scriptSig.elements: if isinstance(e, str): s = e.encode("hex") else: s = str(e) print ' ', s signature, pubKey = tx_in.scriptSig.elements hashType = ord(signature[-1]) signature = signature[:-1] k = Key() k.setPublicKey(pubKey) address = getAddress(k) hash = base58.decodeBase58Check(address, 0) #PUBKEY_ADDRESS = 0 scriptPubKey = btx.Script.standardPubKey(hash) sigHash = tx.getSignatureBodyHash(i, scriptPubKey, hashType, amount=amounts[i]) print ' pubKey: ', pubKey.encode('hex') print ' signature: ', signature.encode('hex') print ' hashType: 0x%0x' % hashType print ' address: ', address print ' sigHash: ', sigHash.encode('hex') print ' valid: ', k.verify(sigHash, signature) print '' for tx_out in tx.tx_out: print 'TxOut:' print ' amount: %s BCC' % str(decimal.Decimal(tx_out.amount) / BCC) elements = tx_out.scriptPubKey.elements print ' script:' for e in elements: if isinstance(e, str): s = e.encode("hex") else: s = '0x%0x' % e print ' ', s if len(elements) == 5 and \ elements[0:2] == [btx.OP.DUP, btx.OP.HASH160] and \ elements[3:5] == [btx.OP.EQUALVERIFY, btx.OP.CHECKSIG] and \ isinstance(elements[2], str): address = base58.encodeBase58Check(elements[2], 0) #PUBKEY_ADDRESS = 0 print ' Address: ', address else: print ' Unrecognized script type' print '' fee = sum(amounts) - sum([tx_out.amount for tx_out in tx.tx_out]) print 'Tx fee: %s BCC' % str(decimal.Decimal(fee) / BCC)