コード例 #1
0
	def test_versionMismatch(self):
		"Test what happens if decode finds an incorrect version number"

		for hash160, address in self.testSet:
			wrongAddress = base58.encodeBase58Check(hash160, 1)

			#Make sure it still works if we use the same version number:
			self.assertEqual(base58.decodeBase58Check(wrongAddress, 1), hash160)

			#But it will fail with a different version number:
			self.assertRaises(Exception, base58.decodeBase58Check,
				wrongAddress, 0
				)
コード例 #2
0
ファイル: timestamp.py プロジェクト: cornwarecjp/amiko-pay
def make(args):
	if len(args) != 2:
		help(["make"])
		sys.exit(1)

	with open(args[0], "rb") as f:
		data = f.read()

	dataHash = crypto.SHA256(crypto.SHA256(data))
	print "Data hash: ", dataHash.encode("hex")

	fee =    10000 #0.1 mBTC = 0.0001 BTC
	connect()

	changeAddress = bitcoind.getNewAddress()
	changeHash = base58.decodeBase58Check(changeAddress, 0) # PUBKEY_ADDRESS = 0

	tx = bitcoinutils.sendToDataPubKey(bitcoind, dataHash, changeHash, fee)
	txID = tx.getTransactionID()[::-1].encode("hex")
	print "Transaction ID: ", txID

	bitcoind.sendRawTransaction(tx.serialize())

	print "Transaction is published. Now we wait for 3 confirmations..."
	confirmations = -1
	while confirmations < 3:
		time.sleep(5)
		try:
			newConfirmations = bitcoind.getTransaction(txID)["confirmations"]
		except KeyError:
			newConfirmations = 0
		if newConfirmations != confirmations:
			print "  %d confirmations" % newConfirmations
		confirmations = newConfirmations

	height = bitcoind.getBlockCount()
	for i in range(1000):
		transactionsInBlock = bitcoind.getTransactionHashesByBlockHeight(height)
		if txID in transactionsInBlock:
			break
		height -= 1
	if txID not in transactionsInBlock:
		raise Exception(
			"Something went wrong: transaction ID not found in the last 1000 blocks")

	print "Block height: ", height

	index = transactionsInBlock.index(txID)
	transactionsInBlock = [binascii.unhexlify(x)[::-1] for x in transactionsInBlock]
	merkleBranch, merkleRoot = getMerkleBranch(transactionsInBlock, index)

	blockInfo = bitcoind.getBlockInfoByBlockHeight(height)
	if blockInfo["merkleroot"] != merkleRoot[::-1].encode("hex"):
		raise Exception("Something went wrong: merkle root value mismatch")

	dt = datetime.utcfromtimestamp(blockInfo["time"])
	timeText = dt.strftime("%A %B %d %I:%M:%S %p %Y (UTC)")

	with open(args[1], "wb") as f:
		f.write("#Timestamp certificate for the file %s\n\n" % args[0])

		f.write("#Double-SHA256 of the file contents:\n")
		f.write("dataHash = %s\n\n" % dataHash.encode("hex"))

		f.write("#The timestamping transaction, containing the above hash:\n")
		f.write("transaction = %s\n\n" % tx.serialize().encode("hex"))

		f.write("#The double-SHA256 of the timestamping transaction:\n")
		f.write("#(This is the same as the transaction ID, with the byte order reversed)\n")
		f.write("transactionHash = %s\n\n" % tx.getTransactionID().encode("hex"))

		f.write("#The Merkle-branch of the timestamping transaction:\n")
		for i in range(len(merkleBranch)):
			left, right = merkleBranch[i]
			f.write("merkle_%d = %s, %s\n" % (i, left.encode("hex"), right.encode("hex")))
		f.write("\n")

		f.write("#The Merkle root of the block:\n")
		f.write("#(byte order is the reverse as typically shown in Bitcoin)\n")
		f.write("merkleRoot = %s\n\n" % merkleRoot.encode("hex"))

		f.write("#The block information:\n")
		f.write("blockHeight = %d\n" % height)
		f.write("blockHash = %s\n" % blockInfo["hash"])
		f.write("blockTime = %d\n\n" % blockInfo["time"])

		f.write("#The timestamp:\n")
		f.write("timestamp = %s\n" % timeText)
コード例 #3
0
ファイル: botg.py プロジェクト: cornwarecjp/amiko-pay
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 = []
	totalAmount = 0
	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))

		totalAmount += int(decimal.Decimal(
			raw_input("Amount in unspent output (mBTC): ")
			) * mBTC)

	print "Total of amounts: %s mBTC" % str(decimal.Decimal(totalAmount)/mBTC)

	fee = int(0.01 * mBTC)
	print "Transaction fee is set to: %s mBTC" % str(decimal.Decimal(fee)/mBTC)

	destAddress = raw_input("Destination address: ")
	destHash = base58.decodeBase58Check(destAddress, 0) #PUBKEY_ADDRESS = 0
	destAmount = int(decimal.Decimal(
			raw_input("Amount to send to destination (mBTC): ")
			) * mBTC)
	if destAmount < 0:
		print "Negative amount is not allowed"
		sys.exit(2)
	if destAmount > totalAmount - fee:
		print "Not enough funds"
		sys.exit(1)

	changeKey = getKey("Address to send change amount to: ")
	changeAddress = getAddress(changeKey)
	changeHash = base58.decodeBase58Check(changeAddress, 0) #PUBKEY_ADDRESS = 0

	tx = btx.Transaction(
		tx_in = [
			btx.TxIn(x[0], x[1])
			for x in inputs
			],
		tx_out = [
			btx.TxOut(destAmount, btx.Script.standardPubKey(destHash))
			]
		)
	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])

	print "Serialized transaction:"
	print tx.serialize().encode("hex")
	print "Transaction ID:", tx.getTransactionID()[::-1].encode("hex")
コード例 #4
0
ファイル: botg.py プロジェクト: cornwarecjp/amiko-pay
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
コード例 #5
0
def make(args):
    if len(args) != 2:
        help(["make"])
        sys.exit(1)

    with open(args[0], "rb") as f:
        data = f.read()

    dataHash = crypto.SHA256(crypto.SHA256(data))
    print "Data hash: ", dataHash.encode("hex")

    fee = 10000  #0.1 mBTC = 0.0001 BTC
    connect()

    changeAddress = bitcoind.getNewAddress()
    changeHash = base58.decodeBase58Check(changeAddress,
                                          0)  # PUBKEY_ADDRESS = 0

    tx = bitcoinutils.sendToDataPubKey(bitcoind, dataHash, changeHash, fee)
    txID = tx.getTransactionID()[::-1].encode("hex")
    print "Transaction ID: ", txID

    bitcoind.sendRawTransaction(tx.serialize())

    print "Transaction is published. Now we wait for 3 confirmations..."
    confirmations = -1
    while confirmations < 3:
        time.sleep(5)
        try:
            newConfirmations = bitcoind.getTransaction(txID)["confirmations"]
        except KeyError:
            newConfirmations = 0
        if newConfirmations != confirmations:
            print "  %d confirmations" % newConfirmations
        confirmations = newConfirmations

    height = bitcoind.getBlockCount()
    for i in range(1000):
        transactionsInBlock = bitcoind.getTransactionHashesByBlockHeight(
            height)
        if txID in transactionsInBlock:
            break
        height -= 1
    if txID not in transactionsInBlock:
        raise Exception(
            "Something went wrong: transaction ID not found in the last 1000 blocks"
        )

    print "Block height: ", height

    index = transactionsInBlock.index(txID)
    transactionsInBlock = [
        binascii.unhexlify(x)[::-1] for x in transactionsInBlock
    ]
    merkleBranch, merkleRoot = getMerkleBranch(transactionsInBlock, index)

    blockInfo = bitcoind.getBlockInfoByBlockHeight(height)
    if blockInfo["merkleroot"] != merkleRoot[::-1].encode("hex"):
        raise Exception("Something went wrong: merkle root value mismatch")

    dt = datetime.utcfromtimestamp(blockInfo["time"])
    timeText = dt.strftime("%A %B %d %I:%M:%S %p %Y (UTC)")

    with open(args[1], "wb") as f:
        f.write("#Timestamp certificate for the file %s\n\n" % args[0])

        f.write("#Double-SHA256 of the file contents:\n")
        f.write("dataHash = %s\n\n" % dataHash.encode("hex"))

        f.write("#The timestamping transaction, containing the above hash:\n")
        f.write("transaction = %s\n\n" % tx.serialize().encode("hex"))

        f.write("#The double-SHA256 of the timestamping transaction:\n")
        f.write(
            "#(This is the same as the transaction ID, with the byte order reversed)\n"
        )
        f.write("transactionHash = %s\n\n" %
                tx.getTransactionID().encode("hex"))

        f.write("#The Merkle-branch of the timestamping transaction:\n")
        for i in range(len(merkleBranch)):
            left, right = merkleBranch[i]
            f.write("merkle_%d = %s, %s\n" %
                    (i, left.encode("hex"), right.encode("hex")))
        f.write("\n")

        f.write("#The Merkle root of the block:\n")
        f.write("#(byte order is the reverse as typically shown in Bitcoin)\n")
        f.write("merkleRoot = %s\n\n" % merkleRoot.encode("hex"))

        f.write("#The block information:\n")
        f.write("blockHeight = %d\n" % height)
        f.write("blockHash = %s\n" % blockInfo["hash"])
        f.write("blockTime = %d\n\n" % blockInfo["time"])

        f.write("#The timestamp:\n")
        f.write("timestamp = %s\n" % timeText)
コード例 #6
0
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 = []
    totalAmount = 0
    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))

        totalAmount += int(
            decimal.Decimal(raw_input("Amount in unspent output (mBTC): ")) *
            mBTC)

    print "Total of amounts: %s mBTC" % str(
        decimal.Decimal(totalAmount) / mBTC)

    fee = int(0.01 * mBTC)
    print "Transaction fee is set to: %s mBTC" % str(
        decimal.Decimal(fee) / mBTC)

    destAddress = raw_input("Destination address: ")
    destHash = base58.decodeBase58Check(destAddress, 0)  #PUBKEY_ADDRESS = 0
    destAmount = int(
        decimal.Decimal(raw_input("Amount to send to destination (mBTC): ")) *
        mBTC)
    if destAmount < 0:
        print "Negative amount is not allowed"
        sys.exit(2)
    if destAmount > totalAmount - fee:
        print "Not enough funds"
        sys.exit(1)

    changeKey = getKey("Address to send change amount to: ")
    changeAddress = getAddress(changeKey)
    changeHash = base58.decodeBase58Check(changeAddress,
                                          0)  #PUBKEY_ADDRESS = 0

    tx = btx.Transaction(
        tx_in=[btx.TxIn(x[0], x[1]) for x in inputs],
        tx_out=[btx.TxOut(destAmount, btx.Script.standardPubKey(destHash))])
    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])

    print "Serialized transaction:"
    print tx.serialize().encode("hex")
    print "Transaction ID:", tx.getTransactionID()[::-1].encode("hex")
コード例 #7
0
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
コード例 #8
0
	def test_decodeBase58Check(self):
		"Test the decodeBase58Check function"

		for hash160, address in self.testSet:
			self.assertEqual(base58.decodeBase58Check(address, 0), hash160)
コード例 #9
0

s = settings.Settings("../../amikopay.conf")
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 the 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")

print base58.encodeBase58Check(RIPEMD160(SHA256(key1.getPublicKey())), 0)
print base58.encodeBase58Check(RIPEMD160(SHA256(key2.getPublicKey())), 0)

amount = int(100000 * float(raw_input("Amount to be transferred (mBTC): ")))
fee = 10000 #0.1 mBTC
コード例 #10
0
ファイル: escrow.py プロジェクト: guruvan/amiko-pay
from amiko.channels import tcd


if len(sys.argv) != 2:
	print "Usage: %s private_key_file" % sys.argv[0]
	sys.exit()


print "Loading the private key...",
with open(sys.argv[1], "rb") as f:
	privateKey = f.read()

#Assume base58 encoded private key on the first line of the file.
#Anything else will be very likely to result in an exception.
privateKey = privateKey.split('\n')[0]
privateKey = base58.decodeBase58Check(privateKey, 128) #PRIVKEY = 128

key = crypto.Key()
key.setPrivateKey(privateKey)

print "done"

print "Our public key is: ", key.getPublicKey().encode("hex")

print "Reading the settings file...",
settings = settings.Settings("amikopay.conf")
bitcoind = bitcoind.Bitcoind(settings)
print "done"

print
WID = raw_input("Enter the withdraw transaction ID: ")