def create_invalid_tx(): """Create and return an invalid transaction. The transaction is invalid because it's missing the signature.""" b = Bigchain() tx = b.create_transaction(b.me, b.me, None, 'CREATE') return tx
def create_write_transaction(tx_left): b = Bigchain() while tx_left > 0: # use uuid to prevent duplicate transactions (transactions with the same hash) tx = b.create_transaction(b.me, b.me, None, 'CREATE', payload={'msg': str(uuid.uuid4())}) tx_signed = b.sign_transaction(tx, b.me_private) b.write_transaction(tx_signed) tx_left -= 1
def transfer_coin(user_vk, user_sk, coin_id): b = Bigchain() coins = get_owned_coins(user_vk) if coin_id in coins.keys(): for tx in coins[coin_id]: tx_input = {'txid': tx['id'], 'cid': 0} tx_transfer = b.create_transaction(user_vk, b.me, tx_input, 'TRANSFER', payload=tx['transaction']['data']['payload']) tx_transfer_signed = b.sign_transaction(tx_transfer, user_sk) b.write_transaction(tx_transfer_signed) print('TRANSFER {} {} {}'.format(tx_transfer_signed['id'], coin_id, tx['transaction']['data']['payload']['coin_share']))
def mint_coin(user_pk): b = Bigchain() coin_id = uuid.uuid4() for i in range(10): payload = { 'coin_id': str(coin_id), 'coin_share': str(i) } tx = b.create_transaction(b.me, user_pk, None, 'CREATE', payload=payload) tx_signed = b.sign_transaction(tx, b.me_private) b.write_transaction(tx_signed) print('MINT {} {} {}'.format(tx['id'], coin_id, i))
def mint_coin(user_pk): b = Bigchain() coin_id = uuid.uuid4() for i in range(10): payload = {'coin_id': str(coin_id), 'coin_share': str(i)} tx = b.create_transaction(b.me, user_pk, None, 'CREATE', payload=payload) tx_signed = b.sign_transaction(tx, b.me_private) b.write_transaction(tx_signed) print('MINT {} {} {}'.format(tx['id'], coin_id, i))
def pay_royalties(label_vk, artist_vk, tx, label_share=7, artist_share=3): b = Bigchain() payload = tx['transaction']['data']['payload'] tx_input = {'txid': tx['id'], 'cid': 0} if int(payload['coin_share']) < artist_share: new_owner = artist_vk else: new_owner = label_vk tx_royalties = b.create_transaction(b.me, new_owner, tx_input, 'TRANSFER', payload=payload) tx_royalties_signed = b.sign_transaction(tx_royalties, b.me_private) b.write_transaction(tx_royalties_signed) print('ROYALTIES {} {} {} {}'.format(tx_royalties['id'], payload['coin_id'], payload['coin_share'], new_owner))
def transfer_coin(user_vk, user_sk, coin_id): b = Bigchain() coins = get_owned_coins(user_vk) if coin_id in coins.keys(): for tx in coins[coin_id]: tx_input = {'txid': tx['id'], 'cid': 0} tx_transfer = b.create_transaction( user_vk, b.me, tx_input, 'TRANSFER', payload=tx['transaction']['data']['payload']) tx_transfer_signed = b.sign_transaction(tx_transfer, user_sk) b.write_transaction(tx_transfer_signed) print('TRANSFER {} {} {}'.format( tx_transfer_signed['id'], coin_id, tx['transaction']['data']['payload']['coin_share']))
from bigchaindb import Bigchain import writeout b = Bigchain() govt_priv, govt_pub = writeout.importData("govt") for x in range(1,8): priv, pub = writeout.importData("user"+str(x)) tx_signed = writeout.importData("user"+str(x)+"vote") tx_retrieved = b.get_transaction(tx_signed['id']) print(tx_retrieved) # create a transfer transaction tx_transfer = b.create_transaction(pub, govt_pub, tx_retrieved['id'], 'TRANSFER') print(tx_transfer) # sign the transaction tx_transfer_signed = b.sign_transaction(tx_transfer, priv) print(tx_transfer_signed) # write the transaction b.write_transaction(tx_transfer_signed) # check if the transaction is already in the bigchain tx_transfer_retrieved = b.get_transaction(tx_transfer_signed['id']) print(tx_transfer_retrieved) data = b.validate_transaction(tx_transfer_signed)
# Translate public key from tag into a bicgchaindb compliant address # Results in '5GjT173hXbwm9R5x2Sk4y6NgeqCCA2JrwdyZdzKPvC6a' prdct_pubkey = binascii.hexlify(tag_pubkey) prdct_pubkey = hashlib.sha3_256(prdct_pubkey).digest() prdct_pubkey = base58.b58encode(prdct_pubkey) # Define a private and public key representing the producer prdusr_privkey, prdusr_pubkey = crypto.generate_key_pair() # Define a private and public key representing a future product owner ownr_privkey, ownr_pubkey = crypto.generate_key_pair() # Create a multisig transaction including the three pre-produced public keys signed with # master key of the BigchainDB instance holder tx_msig = b.create_transaction(b.me, [prdct_pubkey, prdusr_pubkey, ownr_pubkey], None, 'CREATE') # Sign the multisig tx_msig_signed = b.sign_transaction(tx_msig, b.me_private) # Write the signed multig transaction to the federated BigchainDB # Results in {'deleted': 0, 'unchanged': 0, 'errors': 0, 'skipped': 0, 'inserted': 1, 'replaced': 0} b.write_transaction(tx_msig_signed) # Check the uploaded multisig transaction tx_msig_retrieved = b.get_transaction(tx_msig_signed['id']) """ Has to result in JSON string like :
class ChainQuery(object): def __init__(self, host=None, port=None, dbname=None,pub_key=None,priv_key=None,keyring=[], consensus_plugin=None): self.host = host self.port = port self.dbname = dbname self.conn =r.connect(host=host,port=port,db=dbname) self.bigchain=Bigchain(host=host,port=port,dbname=dbname,public_key=pub_key,private_key=priv_key,keyring=keyring,consensus_plugin=consensus_plugin) #test def test(self): tables=r.db('bigchain').table_list().run(self.conn) #print(tables) return tables # create key_pair for user def generate_key_pair(self): return crypto.generate_key_pair() # create asset def create_asset(self,public_key, digital_asset_payload): tx = self.bigchain.create_transaction(self.bigchain.me, public_key, None, 'CREATE', payload=digital_asset_payload) tx_signed = self.bigchain.sign_transaction(tx, self.bigchain.me_private) return self.bigchain.write_transaction(tx_signed) # get transaction by payload_uuid def getTxid_by_payload_uuid(self,payload_uuid): cursor = r.table('bigchain') \ .get_all(payload_uuid, index='payload_uuid') \ .pluck({'block':{'transactions':'id'}}) \ .run(self.conn) transactions = list(cursor) return transactions # get transaction by payload def getTxid_by_payload(self,payload): pass # get currentowner of a payload(assert) def getOwnerofAssert(self,payload): return # get one's assert def get_owned_asserts(self,pub_key): return # if tx contains someone def tx_contains_one(self,tx,one_pub): for condition in tx['conditions']: if one_pub in condition['new_owners']: return True for fullfillment in tx['fulfillments']: if one_pub in fullfillment['current_owners']: return True # transfer assert to another, old_owner create this transaction,so need old_owner's pub/priv key. def transfer_assert(self,old_owner_pub,old_owner_priv,new_owner_pub,tx_id): tx_transfer=self.bigchain.create_transaction(old_owner_pub,new_owner_pub,tx_id,'TRANSFER') tx_transfer_signed=self.bigchain.sign_transaction(tx_transfer,old_owner_priv) #check if the transaction is valid check=self.bigchain.is_valid_transaction(tx_transfer_signed) if check: self.bigchain.write_transaction(tx_transfer_signed) else: logger.info('this transaction is invalid.')
# user A testuser1_priv, testuser1_pub = crypto.generate_key_pair() print("testuser1_priv:" + testuser1_priv) print("testuser1_pub:" + testuser1_pub) payload = { "msg": "first charge for user A", "issue": "charge", "category": "currency", "amount": 300, "asset": "", "account": 0, "previous": "genesis", "trader": "" } tx = b.create_transaction(b.me, testuser1_pub, None, 'CREATE', payload=payload) tx_signed = b.sign_transaction(tx, b.me_private) if b.is_valid_transaction(tx_signed): b.write_transaction(tx_signed) print(tx_signed) # user B testuser2_priv, testuser2_pub = crypto.generate_key_pair() print("testuser2_priv:" + testuser2_priv) print("testuser2_pub:" + testuser2_pub) payload2 = { "msg": "first charge for user B", "issue": "charge", "category": "currency", "amount": 400, "asset": "",
b = Bigchain() """ Create a Digital Asset """ # create a test user testuser1_priv, testuser1_pub = crypto.generate_key_pair() # define a digital asset data payload digital_asset_payload = {'msg': 'Hello BigchainDB!'} # a create transaction uses the operation `CREATE` and has no inputs tx = b.create_transaction(b.me, testuser1_pub, None, 'CREATE', payload=digital_asset_payload) # all transactions need to be signed by the user creating the transaction tx_signed = b.sign_transaction(tx, b.me_private) # write the transaction to the bigchain # the transaction will be stored in a backlog where it will be validated, # included in a block, and written to the bigchain b.write_transaction(tx_signed) sleep(8) """ Read the Creation Transaction from the DB """
def transactions(request, format=None): ''' URL: transactions/ Use for: get or create bill transaction Para: GET: field - filter every json dict operation - CREATE or TRANSFER limit - limit list length, less than 100 sortby - sort by specified field, for timestamp order - the order for sort, asc or des, default asc receive_pubk - public key to get all transactions`id by receive, do not support some paras like limit origin_pubk - public key to get all transactions`id by origin POST: origin_pubk - transaction origin public key, if no this value, will create one CREATE transaction origin_prik - transaction origin private key, if no this value, will create one CREATE transaction pre_txid - previous transaction id receive_pubk - transaction receive public key data - data json string ''' if request.method == 'GET': # get paras fields = request.GET.getlist('field') limit = request.GET.get('limit', None) sortby = request.GET.get('sortby', None) order = request.GET.get('order', None) receive_pubk = request.GET.get('receive_pubk', None) origin_pubk = request.GET.get('origin_pubk', None) operation = request.GET.get('operation', None) # make sort function for rethinkdb driver sort_func = None if sortby != None: sort_func = lambda ts: ts['transaction'][sortby] # make filter filtes_funcs = [] if receive_pubk != None: filtes_funcs.append(lambda x: x['transaction'].contains(lambda x: \ x['conditions'].contains(lambda x: x['new_owners'].\ contains(receive_pubk)))) elif origin_pubk != None: filtes_funcs.append(lambda x: x['transaction'].contains(lambda x: \ x['fulfillments'].contains(lambda x: x['current_owners'].\ contains(origin_pubk)))) if operation != None: filtes_funcs.append(lambda t: t.contains(\ lambda x: x['transaction']['operation'] == operation)) # get datas datas = rdb_select(sortby=sort_func, order=order, filtes=filtes_funcs, keys=['block', 'transactions'], limit=limit) # can`t pluck, limit this data by rethinkdb driver, handle with hand # limit try: limit = int(limit) except TypeError: limit = 100 limit = min(100, limit) # limit less than 100 # return datas by max operation if limit == 1 and sortby != None: return Response(field_filter(datas[0], fields)) # return normal datas, it`s format willbe [[d1, ...], [d2, ..], ...] # change format to [d1, d2, d3...] ans = [] for alist in datas: for data in alist: if len(ans) >= limit: return Response(ans) ans.append(field_filter(data, fields)) # filter data return Response(ans) elif request.method == 'POST': # get paras origin_pubk = request.POST.get('origin_pubk', None) origin_prik = request.POST.get('origin_prik', None) pre_txid = request.POST.get('pre_txid', None) receive_pubk = request.POST.get('receive_pubk', None) data = request.POST.get('data', '{}') # make sure paras receive_prik = '' bdb_input = None bdb_type = 'CREATE' bdb = Bigchain() try: data = json.loads(data) # json string to json data except JSONDecodeError: return error(400, 'Wrong json string format') # bill data format checker left_money = 0 pre_data = None billm = 'Bill_amount_money' bill = 'bill' if billm not in data.keys(): return error(400, 'Wrong data format') # make sure paras if receive_pubk == None: # create a pair receive_prik, receive_pubk = crypto.generate_key_pair() if origin_pubk == None: # create transaction origin_pubk = bdb.me origin_prik = bdb.me_private else: # transfer transaction bdb_type = 'TRANSFER' if origin_prik == None: return error(400, 'need private key') if pre_txid == None: return error(400, 'need pre_txid when transfer') # get previous bill, and check it pre_tx = bdb.get_transaction(pre_txid) if pre_tx == None: return error(400, 'This pre_txid does not exist') # make input, in our case, the key 'cid' will always be 0 bdb_input = {'cid': 0, 'txid': pre_txid} # check bdb_input belong origin if bdb_input not in bdb.get_owned_ids(origin_pubk): return error(400, 'This pre_txid does not belong the origin') # money check pre_data = pre_tx['transaction']['data']['payload'] pre_money = pre_data[bill][billm] now_money = data[billm] if now_money > pre_money: return error(400, 'money to less') left_money = pre_money - now_money # start transaction tx = bdb.create_transaction(origin_pubk, receive_pubk, bdb_input, bdb_type, payload={ 'pre_txid': pre_txid, 'bill': data }) bdb.write_transaction(bdb.sign_transaction(tx, origin_prik)) # create new bill with left money if pre_data != None: # change data pre_data[bill][billm] = left_money pre_data['pre_txid'] = pre_txid ltx = bdb.create_transaction(bdb.me, origin_pubk, None, 'CREATE', payload=pre_data) bdb.write_transaction(bdb.sign_transaction(ltx, bdb.me_private)) return Response({ 'txid': tx['id'], 'receive_pubk': receive_pubk, 'receive_prik': receive_prik })
# user A testuser1_priv, testuser1_pub = crypto.generate_key_pair() print("testuser1_priv:"+testuser1_priv) print("testuser1_pub:"+testuser1_pub) payload = { "msg" : "first charge for user A", "issue" : "charge", "category" : "currency", "amount" : 300, "asset":"", "account":0, "previous":"genesis", "trader":"" } tx = b.create_transaction(b.me, testuser1_pub, None, 'CREATE', payload=payload) tx_signed = b.sign_transaction(tx, b.me_private) if b.is_valid_transaction(tx_signed): b.write_transaction(tx_signed) print(tx_signed) # user B testuser2_priv, testuser2_pub = crypto.generate_key_pair() print("testuser2_priv:"+testuser2_priv) print("testuser2_pub:"+testuser2_pub) payload2 = { "msg" : "first charge for user B", "issue" : "charge", "category" : "currency", "amount" : 400,
from bigchaindb import Bigchain import writeout import random b = Bigchain() random.seed(3) for x in range(1,8): # define a digital asset data payload digital_asset_payload = {'choice': random.randint(0,100)} # a create transaction uses the operation `CREATE` and has no inputs priv, pub = writeout.importData("user"+str(x)) tx = b.create_transaction(b.me, pub, None, 'CREATE', payload=digital_asset_payload) #tx = b.create_transaction(b.me, pub, None, 'CREATE') # all transactions need to be signed by the user creating the transaction tx_signed = b.sign_transaction(tx, b.me_private) writeout.exportData(tx_signed, "user"+str(x)+"vote") # write the transaction to the bigchain # the transaction will be stored in a backlog where it will be validated, # included in a block, and written to the bigchain print(b.write_transaction(tx_signed))
testuser1_last=b.get_owned_ids(testuser1_pub).pop() payload_A = { "msg" : "node send -50 to A,is -50", "issue" : "cost", "category" : "currency", "amount" : 50, "asset":"", # final owner 's account "account":300, "previous":testuser1_last['txid'], "trader":testuser2_pub } tx_create= b.create_transaction(b.me, testuser1_pub, None, 'CREATE', payload=payload_A) tx_create_signed = b.sign_transaction(tx_create, b.me_private) if b.is_valid_transaction(tx_create_signed): b.write_transaction(tx_create_signed) # node create transaction for b, testuser2_last=b.get_owned_ids(testuser2_pub).pop() payload_B = { "msg" : "node send +50 to B,is +50", "issue" : "earn", "category" : "currency", "amount" : 50, "asset":"", # final owner 's account "account":400, "previous":testuser2_last['txid'],
# "NET PRICE": "25" , # "PRICE": "50" , # "QUANTITY": "50000" , # "SIDE": "S" , # "TYPE": "EQ" # }, # ...] data = [] with open('data.csv', 'r') as fid: reader = csv.DictReader(fid) for row in reader: data.append(row) # generate distinct users from the CPTY1 column and assign keys users = [] for user_name in set([d['CPTY1'] for d in data]): sk, vk = b.generate_keys() user = users.append( { 'name': user_name, 'signing_key': sk, 'verifying_key': vk } ) # create assets on the blockchain with the payload and assign to the user for asset in data: user = [u for u in users if u['name'] == asset['CPTY1']][0] tx = b.create_transaction(b.me, user['verifying_key'], None, 'CREATE', payload=asset) tx_signed = b.sign_transaction(tx, b.me_private) b.write_transaction(tx_signed)
from bigchaindb import Bigchain import writeout import random b = Bigchain() random.seed(3) for x in range(1, 8): # define a digital asset data payload digital_asset_payload = {'choice': random.randint(0, 100)} # a create transaction uses the operation `CREATE` and has no inputs priv, pub = writeout.importData("user" + str(x)) tx = b.create_transaction(b.me, pub, None, 'CREATE', payload=digital_asset_payload) #tx = b.create_transaction(b.me, pub, None, 'CREATE') # all transactions need to be signed by the user creating the transaction tx_signed = b.sign_transaction(tx, b.me_private) writeout.exportData(tx_signed, "user" + str(x) + "vote") # write the transaction to the bigchain # the transaction will be stored in a backlog where it will be validated, # included in a block, and written to the bigchain print(b.write_transaction(tx_signed))
class ChainQuery(object): def __init__( self, host=None, port=None, dbname=None, pub_key=None, priv_key=None, keyring=[], consensus_plugin=None ): self.host = host self.port = port self.dbname = dbname self.conn = r.connect(host=host, port=port, db=dbname) self.bigchain = Bigchain( host=host, port=port, dbname=dbname, public_key=pub_key, private_key=priv_key, keyring=keyring, consensus_plugin=consensus_plugin, ) # test def test(self): tables = r.db("bigchain").table_list().run(self.conn) # print(tables) return tables # create key_pair for user def generate_key_pair(self): return crypto.generate_key_pair() # create asset def create_asset(self, public_key, digital_asset_payload): tx = self.bigchain.create_transaction( self.bigchain.me, public_key, None, "CREATE", payload=digital_asset_payload ) tx_signed = self.bigchain.sign_transaction(tx, self.bigchain.me_private) return self.bigchain.write_transaction(tx_signed) # get transaction by payload_uuid def getTxid_by_payload_uuid(self, payload_uuid): cursor = ( r.table("bigchain") .get_all(payload_uuid, index="payload_uuid") .pluck({"block": {"transactions": "id"}}) .run(self.conn) ) transactions = list(cursor) return transactions # get transaction by payload def getTxid_by_payload(self, payload): pass # get currentowner of a payload(assert) def getOwnerofAssert(self, payload): return # get one's assert def get_owned_asserts(self, pub_key): return # if tx contains someone def tx_contains_one(self, tx, one_pub): for condition in tx["conditions"]: if one_pub in condition["new_owners"]: return True for fullfillment in tx["fulfillments"]: if one_pub in fullfillment["current_owners"]: return True # transfer assert to another, old_owner create this transaction,so need old_owner's pub/priv key. def transfer_assert(self, old_owner_pub, old_owner_priv, new_owner_pub, tx_id): tx_transfer = self.bigchain.create_transaction(old_owner_pub, new_owner_pub, tx_id, "TRANSFER") tx_transfer_signed = self.bigchain.sign_transaction(tx_transfer, old_owner_priv) # check if the transaction is valid check = self.bigchain.is_valid_transaction(tx_transfer_signed) if check: self.bigchain.write_transaction(tx_transfer_signed) else: logger.info("this transaction is invalid.")
# setup # pvt_key, pub_key = b.generate_keys() pvt_key2, pub_key2 = b.generate_keys() print("Public Key:", pub_key, "\n") # init # # # db initialization # first transaction - asset creation - required, asset logic not used for our use-case: storing arbitrary data print("DB init - first TX:") asset_payload = {'msg': 'Arbitrary data asset'} tx = b.create_transaction(b.me, pub_key, None, 'CREATE', payload=asset_payload) tx_signed = sign_and_write(tx, b.me_private) print("TX:", tx_signed, "\n") time.sleep(8) # bigchaindb takes a couple of seconds to confirm a transaction tx_retrieved = b.get_transaction(tx_signed['id']) print("TX retrieved:", tx_retrieved, "\n") # main # print("\n\nData TX:") data = { "amount": 123, "date": "2016-01-01" } # <---- arbitrary data, can be encrypted with ecies, ownership based on transaction signer (public key) tx2 = b.create_transaction(pub_key, pub_key, tx_retrieved['id'], 'TRANSFER',