Handcrafting Transactions

For those who wish to assemble transaction payloads “by hand”, with examples in Python.

Overview

Submitting a transaction to a BigchainDB node consists of three main steps:

  1. Preparing the transaction payload;
  2. Fulfilling the prepared transaction payload; and
  3. Sending the transaction payload via HTTPS.

Step 1 and 2 can be performed offline on the client. That is, they do not require any connection to any BigchainDB node.

For convenience’s sake, some utilites are provided to prepare and fulfill a transaction via the BigchainDB class, and via the offchain module. For an introduction on using these utilities, see the Basic Usage Examples or Advanced Usage Examples sections.

The rest of this document will guide you through completing steps 1 and 2 manually by revisiting some of the examples provided in the usage sections. We will:

  • provide all values, including the default ones;
  • generate the transaction id;
  • learn to use crypto-conditions to generate a condition that locks the transaction, hence protecting it from being consumed by an unauthorized user;
  • learn to use crypto-conditions to generate a fulfillment that unlocks the transaction asset, and consequently enact an ownership transfer.

In order to perform all of the above, we’ll use the following Python libraries:

  • json: to serialize the transaction dictionary into a JSON formatted string;
  • sha3: to hash the serialized transaction; and
  • cryptoconditions: to create conditions and fulfillments

High-level view of a transaction in Python

For detailled documentation on the transaction schema, please consult The Transaction Model and The Transaction Schema.

From the point of view of Python, a transaction is simply a dictionary:

{
    'operation': 'CREATE',
    'asset': {
        'data': {
            'bicycle': {
                'manufacturer': 'bkfab',
                'serial_number': 'abcd1234'
            }
        }
    },
    'version': '1.0',
    'outputs': [
        {
            'condition': {
                'details': {
                    'public_key': '2GoYB8cMZQrUBZzx9BH9Bq92eGWXBy3oanDXbRK3YRpW',
                    'type': 'ed25519-sha-256'
                },
                'uri': 'ni:///sha-256;1hBHivh6Nxhgi2b1ndUbP55ZlyUFdLC9BipPUBWth7U?fpt=ed25519-sha-256&cost=131072'
            },
            'public_keys': [
                '2GoYB8cMZQrUBZzx9BH9Bq92eGWXBy3oanDXbRK3YRpW'
            ],
            'amount': '1'
        }
    ],
    'inputs': [
        {
            'fulfills': None,
            'owners_before': [
                '2GoYB8cMZQrUBZzx9BH9Bq92eGWXBy3oanDXbRK3YRpW'
            ],
            'fulfillment': {
                'public_key': '2GoYB8cMZQrUBZzx9BH9Bq92eGWXBy3oanDXbRK3YRpW',
                'type': 'ed25519-sha-256'
            }
        }
    ],
    'id': '52f8ec4d56b4187be256231ef11017038f316d16ef0a0d250e235d39e901f4d1',
    'metadata': {
        'planet': 'earth'
    }
}

Because a transaction must be signed before being sent, the id and fulfillment must be provided by the client.

Important

Implications of Signed Payloads

Because BigchainDB relies on cryptographic signatures, the payloads need to be fully prepared and signed on the client side. This prevents the server(s) from tampering with the provided data.

This enhanced security puts more work on the clients, as various values that could traditionally be generated on the server side need to be generated on the client side.

Bicycle Asset Creation Revisited

The Prepared Transaction

Recall that in order to prepare a transaction, we had to do something similar to:

In [1]: from bigchaindb_driver.crypto import generate_keypair

In [2]: from bigchaindb_driver.offchain import prepare_transaction

In [3]: alice = generate_keypair()

In [4]: bicycle = {
   ...:     'data': {
   ...:         'bicycle': {
   ...:             'serial_number': 'abcd1234',
   ...:             'manufacturer': 'bkfab',
   ...:         },
   ...:     },
   ...: }
   ...: 

In [5]: metadata = {'planet': 'earth'}

In [6]: prepared_creation_tx = prepare_transaction(
   ...:     operation='CREATE',
   ...:     signers=alice.public_key,
   ...:     asset=bicycle,
   ...:     metadata=metadata,
   ...: )
   ...: 

and the payload of the prepared transaction looked similar to:

In [7]: prepared_creation_tx
Out[7]: 
{'asset': {'data': {'bicycle': {'manufacturer': 'bkfab',
    'serial_number': 'abcd1234'}}},
 'id': 'e7e914dde0fb3cb157dccc68a36faf93a26ed3a45e29921f6e7c3e937d7be628',
 'inputs': [{'fulfillment': {'public_key': '94WuEH3gXAqwBKPh6JTPLoi4NHZThr51nTyeSdoBQa81',
    'type': 'ed25519-sha-256'},
   'fulfills': None,
   'owners_before': ['94WuEH3gXAqwBKPh6JTPLoi4NHZThr51nTyeSdoBQa81']}],
 'metadata': {'planet': 'earth'},
 'operation': 'CREATE',
 'outputs': [{'amount': '1',
   'condition': {'details': {'public_key': '94WuEH3gXAqwBKPh6JTPLoi4NHZThr51nTyeSdoBQa81',
     'type': 'ed25519-sha-256'},
    'uri': 'ni:///sha-256;yPNgMgVPiXWFK6yKwF55QQn34piZYJ3w5SKjljvZt6M?fpt=ed25519-sha-256&cost=131072'},
   'public_keys': ['94WuEH3gXAqwBKPh6JTPLoi4NHZThr51nTyeSdoBQa81']}],
 'version': '1.0'}

Note alice‘s public key is listed in the public keys of outputs:

In [8]: alice.public_key
Out[8]: '94WuEH3gXAqwBKPh6JTPLoi4NHZThr51nTyeSdoBQa81'

In [9]: prepared_creation_tx['outputs'][0]['public_keys'][0] == alice.public_key
Out[9]: True

We are now going to craft this payload by hand.

version

As of BigchainDB 1.0, the transaction version is set to 1.0.

In [10]: version = '1.0'

asset

Because this is a CREATE transaction, we provide the data payload for the asset to the transaction (see the transfer example below for how to construct assets in TRANSFER transactions):

In [11]: asset = {
   ....:     'data': {
   ....:         'bicycle': {
   ....:             'manufacturer': 'bkfab',
   ....:             'serial_number': 'abcd1234',
   ....:         },
   ....:     },
   ....: }
   ....: 

metadata

In [12]: metadata = {'planet': 'earth'}

operation

In [13]: operation = 'CREATE'

Important

Case sensitive; all letters must be capitalized.

outputs

The purpose of the output condition is to lock the transaction, such that a valid input fulfillment is required to unlock it. In the case of signature-based schemes, the lock is basically a public key, such that in order to unlock the transaction one needs to have the private key.

Let’s review the output payload of the prepared transaction, to see what we are aiming for:

In [14]: prepared_creation_tx['outputs'][0]
Out[14]: 
{'amount': '1',
 'condition': {'details': {'public_key': '94WuEH3gXAqwBKPh6JTPLoi4NHZThr51nTyeSdoBQa81',
   'type': 'ed25519-sha-256'},
  'uri': 'ni:///sha-256;yPNgMgVPiXWFK6yKwF55QQn34piZYJ3w5SKjljvZt6M?fpt=ed25519-sha-256&cost=131072'},
 'public_keys': ['94WuEH3gXAqwBKPh6JTPLoi4NHZThr51nTyeSdoBQa81']}

The difficult parts are the condition details and URI. We’‘ll now see how to generate them using the cryptoconditions library:

Note

In BigchainDB keys are encoded in base58 but the cryptoconditions library expects an unencoded byte string so we will have to decode the base58 key before we can use it with cryptoconditions.

In [15]: import base58

A base58 encoded key:

In [16]: alice.public_key
Out[16]: '94WuEH3gXAqwBKPh6JTPLoi4NHZThr51nTyeSdoBQa81'

Becomes:

In [17]: base58.b58decode(alice.public_key)
Out[17]: b'w\xc4\x0b\xe3s\x8dX\xd2\xd1R\xefF\xee\xe3\x9a\x9cy\xad\xb7n+\xd5\x06C\xf5@\xd9\x12\xc3u\xfe\xb2'
In [18]: from cryptoconditions import Ed25519Sha256

In [19]: ed25519 = Ed25519Sha256(public_key=base58.b58decode(alice.public_key))

generate the condition URI:

In [20]: ed25519.condition_uri
Out[20]: 'ni:///sha-256;yPNgMgVPiXWFK6yKwF55QQn34piZYJ3w5SKjljvZt6M?fpt=ed25519-sha-256&cost=131072'

So now you have a condition URI for Alice’s public key.

As for the details:

In [21]: condition_details = {
   ....:     'type': ed25519.TYPE_NAME,
   ....:     'public_key': base58.b58encode(ed25519.public_key),
   ....: }
   ....: 

We can now easily assemble the dict for the output:

In [22]: output = {
   ....:     'amount': '1',
   ....:     'condition': {
   ....:         'details': condition_details,
   ....:         'uri': ed25519.condition_uri,
   ....:     },
   ....:     'public_keys': (alice.public_key,),
   ....: }
   ....: 

Let’s recap and set the outputs key with our self-constructed condition:

In [23]: from cryptoconditions import Ed25519Sha256

In [24]: ed25519 = Ed25519Sha256(public_key=base58.b58decode(alice.public_key))

In [25]: output = {
   ....:     'amount': '1',
   ....:     'condition': {
   ....:         'details': {
   ....:             'type': ed25519.TYPE_NAME,
   ....:             'public_key': base58.b58encode(ed25519.public_key),
   ....:         },
   ....:         'uri': ed25519.condition_uri,
   ....:     },
   ....:     'public_keys': (alice.public_key,),
   ....: }
   ....: 

In [26]: outputs = (output,)

The key part is the condition URI:

In [27]: ed25519.condition_uri
Out[27]: 'ni:///sha-256;yPNgMgVPiXWFK6yKwF55QQn34piZYJ3w5SKjljvZt6M?fpt=ed25519-sha-256&cost=131072'

To know more about its meaning, you may read the cryptoconditions internet draft.

inputs

The input fulfillment for a CREATE operation is somewhat special, and simplified:

In [28]: input_ = {
   ....:     'fulfillment': None,
   ....:     'fulfills': None,
   ....:     'owners_before': (alice.public_key,)
   ....: }
   ....: 
  • The fulfills field is empty because it’s a CREATE operation;
  • The 'fulfillment' value is None as it will be set during the fulfillment step; and
  • The 'owners_before' field identifies the issuer(s) of the asset that is being created.

The inputs value is simply a list or tuple of all inputs:

In [29]: inputs = (input_,)

Note

You may rightfully observe that the input generated in prepared_creation_tx via prepare_transaction() differs:

In [30]: prepared_creation_tx['inputs'][0]
Out[30]: 
{'fulfillment': {'public_key': '94WuEH3gXAqwBKPh6JTPLoi4NHZThr51nTyeSdoBQa81',
  'type': 'ed25519-sha-256'},
 'fulfills': None,
 'owners_before': ['94WuEH3gXAqwBKPh6JTPLoi4NHZThr51nTyeSdoBQa81']}

More precisely, the value of 'fulfillment' is not None:

In [31]: prepared_creation_tx['inputs'][0]['fulfillment']
Out[31]: 
{'public_key': '94WuEH3gXAqwBKPh6JTPLoi4NHZThr51nTyeSdoBQa81',
 'type': 'ed25519-sha-256'}

The quick answer is that it simply is not needed, and can be set to None.

Up to now

Putting it all together:

In [32]: handcrafted_creation_tx = {
   ....:     'asset': asset,
   ....:     'metadata': metadata,
   ....:     'operation': operation,
   ....:     'outputs': outputs,
   ....:     'inputs': inputs,
   ....:     'version': version,
   ....: }
   ....: 

In [33]: handcrafted_creation_tx
Out[33]: 
{'asset': {'data': {'bicycle': {'manufacturer': 'bkfab',
    'serial_number': 'abcd1234'}}},
 'inputs': ({'fulfillment': None,
   'fulfills': None,
   'owners_before': ('94WuEH3gXAqwBKPh6JTPLoi4NHZThr51nTyeSdoBQa81',)},),
 'metadata': {'planet': 'earth'},
 'operation': 'CREATE',
 'outputs': ({'amount': '1',
   'condition': {'details': {'public_key': '94WuEH3gXAqwBKPh6JTPLoi4NHZThr51nTyeSdoBQa81',
     'type': 'ed25519-sha-256'},
    'uri': 'ni:///sha-256;yPNgMgVPiXWFK6yKwF55QQn34piZYJ3w5SKjljvZt6M?fpt=ed25519-sha-256&cost=131072'},
   'public_keys': ('94WuEH3gXAqwBKPh6JTPLoi4NHZThr51nTyeSdoBQa81',)},),
 'version': '1.0'}

The only thing we’re missing now is the id. We’ll generate it soon, but before that, let’s recap how we’ve put all the code together to generate the above payload:

from cryptoconditions import Ed25519Sha256
from bigchaindb_driver.crypto import CryptoKeypair

alice = CryptoKeypair(
    public_key=alice.public_key,
    private_key=alice.private_key,
)

operation = 'CREATE'

version = '1.0'

asset = {
    'data': {
        'bicycle': {
            'manufacturer': 'bkfab',
            'serial_number': 'abcd1234',
        },
    },
}

metadata = {'planet': 'earth'}

ed25519 = Ed25519Sha256(public_key=base58.b58decode(alice.public_key))

output = {
    'amount': '1',
    'condition': {
        'details': {
            'type': ed25519.TYPE_NAME,
            'public_key': base58.b58encode(ed25519.public_key),
        },
        'uri': ed25519.condition_uri,
    },
    'public_keys': (alice.public_key,),
}
outputs = (output,)

input_ = {
    'fulfillment': None,
    'fulfills': None,
    'owners_before': (alice.public_key,)
}
inputs = (input_,)

handcrafted_creation_tx = {
    'asset': asset,
    'metadata': metadata,
    'operation': operation,
    'outputs': outputs,
    'inputs': inputs,
    'version': version,
}

id

The transaction’s id is essentially a SHA3-256 hash of the entire transaction (up to now), with a few additional tweaks:

In [34]: import json

In [35]: from sha3 import sha3_256

In [36]: json_str_tx = json.dumps(
   ....:     handcrafted_creation_tx,
   ....:     sort_keys=True,
   ....:     separators=(',', ':'),
   ....:     ensure_ascii=False,
   ....: )
   ....: 

In [37]: txid = sha3_256(json_str_tx.encode()).hexdigest()

In [38]: handcrafted_creation_tx['id'] = txid

Compare this to the txid of the transaction generated via prepare_transaction():

In [39]: txid == prepared_creation_tx['id']
Out[39]: True

You may observe that

In [40]: handcrafted_creation_tx == prepared_creation_tx
Out[40]: False
In [41]: from copy import deepcopy

In [42]: # back up

In [43]: prepared_creation_tx_bk = deepcopy(prepared_creation_tx)

In [44]: # set input fulfillment to None

In [45]: prepared_creation_tx['inputs'][0]['fulfillment'] = None

In [46]: handcrafted_creation_tx == prepared_creation_tx
Out[46]: False

Are still not equal because we used tuples instead of lists.

In [47]: # serialize to json str

In [48]: json_str_handcrafted_tx = json.dumps(handcrafted_creation_tx, sort_keys=True)

In [49]: json_str_prepared_tx = json.dumps(prepared_creation_tx, sort_keys=True)
In [50]: json_str_handcrafted_tx == json_str_prepared_tx
Out[50]: True

In [51]: prepared_creation_tx = prepared_creation_tx_bk

The fully handcrafted, yet-to-be-fulfilled CREATE transaction payload:

In [52]: handcrafted_creation_tx
Out[52]: 
{'asset': {'data': {'bicycle': {'manufacturer': 'bkfab',
    'serial_number': 'abcd1234'}}},
 'id': 'e7e914dde0fb3cb157dccc68a36faf93a26ed3a45e29921f6e7c3e937d7be628',
 'inputs': ({'fulfillment': None,
   'fulfills': None,
   'owners_before': ('94WuEH3gXAqwBKPh6JTPLoi4NHZThr51nTyeSdoBQa81',)},),
 'metadata': {'planet': 'earth'},
 'operation': 'CREATE',
 'outputs': ({'amount': '1',
   'condition': {'details': {'public_key': '94WuEH3gXAqwBKPh6JTPLoi4NHZThr51nTyeSdoBQa81',
     'type': 'ed25519-sha-256'},
    'uri': 'ni:///sha-256;yPNgMgVPiXWFK6yKwF55QQn34piZYJ3w5SKjljvZt6M?fpt=ed25519-sha-256&cost=131072'},
   'public_keys': ('94WuEH3gXAqwBKPh6JTPLoi4NHZThr51nTyeSdoBQa81',)},),
 'version': '1.0'}

The Fulfilled Transaction

In [53]: from cryptoconditions.crypto import Ed25519SigningKey

In [54]: # fulfill prepared transaction

In [55]: from bigchaindb_driver.offchain import fulfill_transaction

In [56]: fulfilled_creation_tx = fulfill_transaction(
   ....:     prepared_creation_tx,
   ....:     private_keys=alice.private_key,
   ....: )
   ....: 

In [57]: # fulfill handcrafted transaction (with our previously built ED25519 fulfillment)

In [58]: ed25519.to_dict()
Out[58]: 
{'public_key': '94WuEH3gXAqwBKPh6JTPLoi4NHZThr51nTyeSdoBQa81',
 'signature': None,
 'type': 'ed25519-sha-256'}

In [59]: message = json.dumps(
   ....:     handcrafted_creation_tx,
   ....:     sort_keys=True,
   ....:     separators=(',', ':'),
   ....:     ensure_ascii=False,
   ....: )
   ....: 

In [60]: ed25519.sign(message.encode(), base58.b58decode(alice.private_key))
Out[60]: b"o\xf0\xf6S\xa3yk\x9fo\xa9\x18\xe9\xd1\xed\xc6(\x0bLT\xb3'\x98\x85\x86\xd5\xa5G\xf8\x10\xa9]\x97\xa6\x9e\x96?\xbfz\xd9n\xbb\x1f)=Og\xc3\x86\x98\x15l\x899\x94C\xfe\xf6\xa6<T\x96\xa84\x0e"

In [61]: fulfillment_uri = ed25519.serialize_uri()

In [62]: handcrafted_creation_tx['inputs'][0]['fulfillment'] = fulfillment_uri

Let’s check this:

In [63]: fulfilled_creation_tx['inputs'][0]['fulfillment'] == fulfillment_uri
Out[63]: True

In [64]: json.dumps(fulfilled_creation_tx, sort_keys=True) == json.dumps(handcrafted_creation_tx, sort_keys=True)
Out[64]: True

The fulfilled transaction, ready to be sent over to a BigchainDB node:

In [65]: fulfilled_creation_tx
Out[65]: 
{'asset': {'data': {'bicycle': {'manufacturer': 'bkfab',
    'serial_number': 'abcd1234'}}},
 'id': 'e7e914dde0fb3cb157dccc68a36faf93a26ed3a45e29921f6e7c3e937d7be628',
 'inputs': [{'fulfillment': 'pGSAIHfEC-NzjVjS0VLvRu7jmpx5rbduK9UGQ_VA2RLDdf6ygUBv8PZTo3lrn2-pGOnR7cYoC0xUsyeYhYbVpUf4EKldl6aelj-_etluux8pPU9nw4aYFWyJOZRD_vamPFSWqDQO',
   'fulfills': None,
   'owners_before': ['94WuEH3gXAqwBKPh6JTPLoi4NHZThr51nTyeSdoBQa81']}],
 'metadata': {'planet': 'earth'},
 'operation': 'CREATE',
 'outputs': [{'amount': '1',
   'condition': {'details': {'public_key': '94WuEH3gXAqwBKPh6JTPLoi4NHZThr51nTyeSdoBQa81',
     'type': 'ed25519-sha-256'},
    'uri': 'ni:///sha-256;yPNgMgVPiXWFK6yKwF55QQn34piZYJ3w5SKjljvZt6M?fpt=ed25519-sha-256&cost=131072'},
   'public_keys': ['94WuEH3gXAqwBKPh6JTPLoi4NHZThr51nTyeSdoBQa81']}],
 'version': '1.0'}

In a nutshell

Handcrafting a CREATE transaction can be done as follows:

import json

import base58
import sha3
from cryptoconditions import Ed25519Sha256

from bigchaindb_driver.crypto import generate_keypair


alice = generate_keypair()

operation = 'CREATE'

version = '1.0'

asset = {
    'data': {
        'bicycle': {
            'manufacturer': 'bkfab',
            'serial_number': 'abcd1234',
        },
    },
}

metadata = {'planet': 'earth'}

ed25519 = Ed25519Sha256(public_key=base58.b58decode(alice.public_key))

output = {
    'amount': '1',
    'condition': {
        'details': {
            'type': ed25519.TYPE_NAME,
            'public_key': base58.b58encode(ed25519.public_key),
        },
        'uri': ed25519.condition_uri,
    },
    'public_keys': (alice.public_key,),
}
outputs = (output,)

input_ = {
    'fulfillment': None,
    'fulfills': None,
    'owners_before': (alice.public_key,)
}
inputs = (input_,)

handcrafted_creation_tx = {
    'asset': asset,
    'metadata': metadata,
    'operation': operation,
    'outputs': outputs,
    'inputs': inputs,
    'version': version,
}

json_str_tx = json.dumps(
    handcrafted_creation_tx,
    sort_keys=True,
    separators=(',', ':'),
    ensure_ascii=False,
)

creation_txid = sha3.sha3_256(json_str_tx.encode()).hexdigest()

handcrafted_creation_tx['id'] = creation_txid

message = json.dumps(
    handcrafted_creation_tx,
    sort_keys=True,
    separators=(',', ':'),
    ensure_ascii=False,
)

ed25519.sign(message.encode(), base58.b58decode(alice.private_key))

fulfillment_uri = ed25519.serialize_uri()

handcrafted_creation_tx['inputs'][0]['fulfillment'] = fulfillment_uri

Sending it over to a BigchainDB node:

from bigchaindb_driver import BigchainDB

bdb = BigchainDB('http://bdb-server:9984')
returned_creation_tx = bdb.transactions.send(handcrafted_creation_tx)

A few checks:

>>> json.dumps(returned_creation_tx, sort_keys=True) == json.dumps(handcrafted_creation_tx, sort_keys=True)
True
>>> bdb.transactions.status(creation_txid)
{'status': 'valid'}

Tip

When checking for the status of a transaction, one should keep in mind tiny delays before a transaction reaches a valid status.

Bicycle Asset Transfer Revisited

In the bicycle transfer example , we showed that the transfer transaction was prepared and fulfilled as follows:

In [66]: creation_tx = fulfilled_creation_tx

In [67]: bob = generate_keypair()

In [68]: output_index = 0

In [69]: output = creation_tx['outputs'][output_index]

In [70]: transfer_input = {
   ....:     'fulfillment': output['condition']['details'],
   ....:     'fulfills': {
   ....:          'output_index': output_index,
   ....:          'transaction_id': creation_tx['id'],
   ....:      },
   ....:      'owners_before': output['public_keys'],
   ....: }
   ....: 

In [71]: transfer_asset = {
   ....:     'id': creation_tx['id'],
   ....: }
   ....: 

In [72]: prepared_transfer_tx = prepare_transaction(
   ....:     operation='TRANSFER',
   ....:     asset=transfer_asset,
   ....:     inputs=transfer_input,
   ....:     recipients=bob.public_key,
   ....: )
   ....: 

In [73]: fulfilled_transfer_tx = fulfill_transaction(
   ....:     prepared_transfer_tx,
   ....:     private_keys=alice.private_key,
   ....: )
   ....: 

In [74]: fulfilled_transfer_tx
Out[74]: 
{'asset': {'id': 'e7e914dde0fb3cb157dccc68a36faf93a26ed3a45e29921f6e7c3e937d7be628'},
 'id': '27cc0f2fef314dfc37ade573d8e26637b42d3981ec1d81c6770399e71347eb14',
 'inputs': [{'fulfillment': 'pGSAIHfEC-NzjVjS0VLvRu7jmpx5rbduK9UGQ_VA2RLDdf6ygUDVqBA5oyjqdUcXSGL1gMYuaiaVJvHIyRmvkVE3QaB7Z_Rn3c_tZY5UlWI8PbmZM9e83X17Er_Fw9YY7k_rT1ME',
   'fulfills': {'output_index': 0,
    'transaction_id': 'e7e914dde0fb3cb157dccc68a36faf93a26ed3a45e29921f6e7c3e937d7be628'},
   'owners_before': ['94WuEH3gXAqwBKPh6JTPLoi4NHZThr51nTyeSdoBQa81']}],
 'metadata': None,
 'operation': 'TRANSFER',
 'outputs': [{'amount': '1',
   'condition': {'details': {'public_key': '6Fv2GTqhFcTKwYdQbWftZPSaLcJRY4SwU44BLwhANXy7',
     'type': 'ed25519-sha-256'},
    'uri': 'ni:///sha-256;6Niyb43YjlYyRkevsPiExjIsRW0V34yTuAjDU-gnzcc?fpt=ed25519-sha-256&cost=131072'},
   'public_keys': ['6Fv2GTqhFcTKwYdQbWftZPSaLcJRY4SwU44BLwhANXy7']}],
 'version': '1.0'}

Our goal is now to handcraft a payload equal to fulfilled_transfer_tx with the help of

  • json: to serialize the transaction dictionary into a JSON formatted string.
  • sha3: to hash the serialized transaction
  • cryptoconditions: to create conditions and fulfillments

The Prepared Transaction

version

In [75]: version = '1.0'

asset

The asset payload for TRANSFER transaction is a dict with only the asset id (i.e. the id of the CREATE transaction for the asset):

In [76]: asset = {'id': creation_tx['id']}

metadata

In [77]: metadata = None

operation

In [78]: operation = 'TRANSFER'

outputs

In [79]: from cryptoconditions import Ed25519Sha256

In [80]: ed25519 = Ed25519Sha256(public_key=base58.b58decode(bob.public_key))

In [81]: output = {
   ....:     'amount': '1',
   ....:     'condition': {
   ....:         'details': {
   ....:             'type': ed25519.TYPE_NAME,
   ....:             'public_key': base58.b58encode(ed25519.public_key),
   ....:         },
   ....:         'uri': ed25519.condition_uri,
   ....:     },
   ....:     'public_keys': (bob.public_key,),
   ....: }
   ....: 

In [82]: outputs = (output,)

fulfillments

In [83]: input_ = {
   ....:     'fulfillment': None,
   ....:     'fulfills': {
   ....:         'transaction_id': creation_tx['id'],
   ....:         'output_index': 0,
   ....:     },
   ....:     'owners_before': (alice.public_key,)
   ....: }
   ....: 

In [84]: inputs = (input_,)

A few notes:

  • The fulfills field points to the condition (in a transaction) that needs to be fulfilled;
  • The 'fulfillment' value is None as it will be set during the fulfillment step; and
  • The 'owners_before' field identifies the fulfiller(s).

Putting it all together:

In [85]: handcrafted_transfer_tx = {
   ....:     'asset': asset,
   ....:     'metadata': metadata,
   ....:     'operation': operation,
   ....:     'outputs': outputs,
   ....:     'inputs': inputs,
   ....:     'version': version,
   ....: }
   ....: 

In [86]: handcrafted_transfer_tx
Out[86]: 
{'asset': {'id': 'e7e914dde0fb3cb157dccc68a36faf93a26ed3a45e29921f6e7c3e937d7be628'},
 'inputs': ({'fulfillment': None,
   'fulfills': {'output_index': 0,
    'transaction_id': 'e7e914dde0fb3cb157dccc68a36faf93a26ed3a45e29921f6e7c3e937d7be628'},
   'owners_before': ('94WuEH3gXAqwBKPh6JTPLoi4NHZThr51nTyeSdoBQa81',)},),
 'metadata': None,
 'operation': 'TRANSFER',
 'outputs': ({'amount': '1',
   'condition': {'details': {'public_key': '6Fv2GTqhFcTKwYdQbWftZPSaLcJRY4SwU44BLwhANXy7',
     'type': 'ed25519-sha-256'},
    'uri': 'ni:///sha-256;6Niyb43YjlYyRkevsPiExjIsRW0V34yTuAjDU-gnzcc?fpt=ed25519-sha-256&cost=131072'},
   'public_keys': ('6Fv2GTqhFcTKwYdQbWftZPSaLcJRY4SwU44BLwhANXy7',)},),
 'version': '1.0'}

Up to now

Before we generate the id, let’s recap how we got here:

from cryptoconditions import Ed25519Sha256
from bigchaindb_driver.crypto import CryptoKeypair

bob = CryptoKeypair(
    public_key=bob.public_key,
    private_key=bob.private_key,
)

operation = 'TRANSFER'
version = '1.0'
asset = {'id': creation_tx['id']}
metadata = None

ed25519 = Ed25519Sha256(public_key=base58.b58decode(bob.public_key))

output = {
    'amount': '1',
    'condition': {
        'details': {
            'type': ed25519.TYPE_NAME,
            'public_key': base58.b58encode(ed25519.public_key),
        },
        'uri': ed25519.condition_uri,
    },
    'public_keys': (bob.public_key,),
}
outputs = (output,)

input_ = {
    'fulfillment': None,
    'fulfills': {
        'transaction_id': creation_tx['id'],
        'output_index': 0,
    },
    'owners_before': (alice.public_key,)
}
inputs = (input_,)

handcrafted_transfer_tx = {
    'asset': asset,
    'metadata': metadata,
    'operation': operation,
    'outputs': outputs,
    'inputs': inputs,
    'version': version,
}

id

In [87]: import json

In [88]: from sha3 import sha3_256

In [89]: json_str_tx = json.dumps(
   ....:     handcrafted_transfer_tx,
   ....:     sort_keys=True,
   ....:     separators=(',', ':'),
   ....:     ensure_ascii=False,
   ....: )
   ....: 

In [90]: txid = sha3_256(json_str_tx.encode()).hexdigest()

In [91]: handcrafted_transfer_tx['id'] = txid

Compare this to the txid of the transaction generated via prepare_transaction()

In [92]: txid == prepared_transfer_tx['id']
Out[92]: True

You may observe that

In [93]: handcrafted_transfer_tx == prepared_transfer_tx
Out[93]: False
In [94]: from copy import deepcopy

In [95]: # back up

In [96]: prepared_transfer_tx_bk = deepcopy(prepared_transfer_tx)

In [97]: # set fulfillment to None

In [98]: prepared_transfer_tx['inputs'][0]['fulfillment'] = None

In [99]: handcrafted_transfer_tx == prepared_transfer_tx
Out[99]: False

Are still not equal because we used tuples instead of lists.

In [100]: # serialize to json str

In [101]: json_str_handcrafted_tx = json.dumps(handcrafted_transfer_tx, sort_keys=True)

In [102]: json_str_prepared_tx = json.dumps(prepared_transfer_tx, sort_keys=True)
In [103]: json_str_handcrafted_tx == json_str_prepared_tx
Out[103]: True

In [104]: prepared_transfer_tx = prepared_transfer_tx_bk

The fully handcrafted, yet-to-be-fulfilled TRANSFER transaction payload:

In [105]: handcrafted_transfer_tx
Out[105]: 
{'asset': {'id': 'e7e914dde0fb3cb157dccc68a36faf93a26ed3a45e29921f6e7c3e937d7be628'},
 'id': '27cc0f2fef314dfc37ade573d8e26637b42d3981ec1d81c6770399e71347eb14',
 'inputs': ({'fulfillment': None,
   'fulfills': {'output_index': 0,
    'transaction_id': 'e7e914dde0fb3cb157dccc68a36faf93a26ed3a45e29921f6e7c3e937d7be628'},
   'owners_before': ('94WuEH3gXAqwBKPh6JTPLoi4NHZThr51nTyeSdoBQa81',)},),
 'metadata': None,
 'operation': 'TRANSFER',
 'outputs': ({'amount': '1',
   'condition': {'details': {'public_key': '6Fv2GTqhFcTKwYdQbWftZPSaLcJRY4SwU44BLwhANXy7',
     'type': 'ed25519-sha-256'},
    'uri': 'ni:///sha-256;6Niyb43YjlYyRkevsPiExjIsRW0V34yTuAjDU-gnzcc?fpt=ed25519-sha-256&cost=131072'},
   'public_keys': ('6Fv2GTqhFcTKwYdQbWftZPSaLcJRY4SwU44BLwhANXy7',)},),
 'version': '1.0'}

The Fulfilled Transaction

In [106]: from bigchaindb_driver.offchain import fulfill_transaction

In [107]: # fulfill prepared transaction

In [108]: fulfilled_transfer_tx = fulfill_transaction(
   .....:     prepared_transfer_tx,
   .....:     private_keys=alice.private_key,
   .....: )
   .....: 

In [109]: # fulfill handcrafted transaction (with our previously built ED25519 fulfillment)

In [110]: ed25519.to_dict()
Out[110]: 
{'public_key': '6Fv2GTqhFcTKwYdQbWftZPSaLcJRY4SwU44BLwhANXy7',
 'signature': None,
 'type': 'ed25519-sha-256'}

In [111]: message = json.dumps(
   .....:     handcrafted_transfer_tx,
   .....:     sort_keys=True,
   .....:     separators=(',', ':'),
   .....:     ensure_ascii=False,
   .....: )
   .....: 

In [112]: ed25519.sign(message.encode(), base58.b58decode(alice.private_key))
Out[112]: b'\xd5\xa8\x109\xa3(\xeauG\x17Hb\xf5\x80\xc6.j&\x95&\xf1\xc8\xc9\x19\xaf\x91Q7A\xa0{g\xf4g\xdd\xcf\xede\x8eT\x95b<=\xb9\x993\xd7\xbc\xdd}{\x12\xbf\xc5\xc3\xd6\x18\xeeO\xebOS\x04'

In [113]: fulfillment_uri = ed25519.serialize_uri()

In [114]: handcrafted_transfer_tx['inputs'][0]['fulfillment'] = fulfillment_uri

Let’s check this:

In [115]: fulfilled_transfer_tx['inputs'][0]['fulfillment'] == fulfillment_uri
Out[115]: True

In [116]: json.dumps(fulfilled_transfer_tx, sort_keys=True) == json.dumps(handcrafted_transfer_tx, sort_keys=True)
Out[116]: True

In a nutshell

import json

import base58
import sha3
from cryptoconditions import Ed25519Sha256

from bigchaindb_driver.crypto import generate_keypair


bob = generate_keypair()

operation = 'TRANSFER'
version = '1.0'
asset = {'id': handcrafted_creation_tx['id']}
metadata = None

ed25519 = Ed25519Sha256(public_key=base58.b58decode(bob.public_key))

output = {
    'amount': '1',
    'condition': {
        'details': {
            'type': ed25519.TYPE_NAME,
            'public_key': base58.b58encode(ed25519.public_key),
        },
        'uri': ed25519.condition_uri,
    },
    'public_keys': (bob.public_key,),
}
outputs = (output,)

input_ = {
    'fulfillment': None,
    'fulfills': {
        'transaction_id': creation_txid,
        'output_index': 0,
    },
    'owners_before': (alice.public_key,)
}
inputs = (input_,)

handcrafted_transfer_tx = {
    'asset': asset,
    'metadata': metadata,
    'operation': operation,
    'outputs': outputs,
    'inputs': inputs,
    'version': version,
}

json_str_tx = json.dumps(
    handcrafted_transfer_tx,
    sort_keys=True,
    separators=(',', ':'),
    ensure_ascii=False,
)

transfer_txid = sha3.sha3_256(json_str_tx.encode()).hexdigest()

handcrafted_transfer_tx['id'] = transfer_txid

message = json.dumps(
    handcrafted_transfer_tx,
    sort_keys=True,
    separators=(',', ':'),
    ensure_ascii=False,
)

ed25519.sign(message.encode(), base58.b58decode(alice.private_key))

fulfillment_uri = ed25519.serialize_uri()

handcrafted_transfer_tx['inputs'][0]['fulfillment'] = fulfillment_uri

Sending it over to a BigchainDB node:

from bigchaindb_driver import BigchainDB

bdb = BigchainDB('http://bdb-server:9984')
returned_transfer_tx = bdb.transactions.send(handcrafted_transfer_tx)

A few checks:

>>> json.dumps(returned_transfer_tx, sort_keys=True) == json.dumps(handcrafted_transfer_tx, sort_keys=True)
True
>>> bdb.transactions.status(transfer_txid)
{'status': 'valid'}

Tip

When checking for the status of a transaction, one should keep in mind tiny delays before a transaction reaches a valid status.

Bicycle Sharing Revisited

Handcrafting the CREATE transaction for our bicycle sharing example:

import json

import sha3
from cryptoconditions import Ed25519Sha256

from bigchaindb_driver.crypto import generate_keypair


bob, carly = generate_keypair(), generate_keypair()
version = '1.0'

asset = {
    'data': {
        'token_for': {
            'bicycle': {
                'manufacturer': 'bkfab',
                'serial_number': 'abcd1234',
            },
            'description': 'time share token. each token equals 1 hour of riding.'
        },
    },
}

# CRYPTO-CONDITIONS: instantiate an Ed25519 crypto-condition for carly
ed25519 = Ed25519Sha256(public_key=base58.b58decode(carly.public_key))

# CRYPTO-CONDITIONS: generate the condition uri
condition_uri = ed25519.condition.serialize_uri()

# CRYPTO-CONDITIONS: construct an unsigned fulfillment dictionary
unsigned_fulfillment_dict = {
    'type': ed25519.TYPE_NAME,
    'public_key': base58.b58encode(ed25519.public_key),
}

output = {
    'amount': '10',
    'condition': {
        'details': unsigned_fulfillment_dict,
        'uri': condition_uri,
    },
    'public_keys': (carly.public_key,),
}

input_ = {
    'fulfillment': None,
    'fulfills': None,
    'owners_before': (bob.public_key,)
}

token_creation_tx = {
    'operation': 'CREATE',
    'asset': asset,
    'metadata': None,
    'outputs': (output,),
    'inputs': (input_,),
    'version': version,
}

# JSON: serialize the id-less transaction to a json formatted string
json_str_tx = json.dumps(
    token_creation_tx,
    sort_keys=True,
    separators=(',', ':'),
    ensure_ascii=False,
)

# SHA3: hash the serialized id-less transaction to generate the id
creation_txid = sha3.sha3_256(json_str_tx.encode()).hexdigest()

# add the id
token_creation_tx['id'] = creation_txid

# JSON: serialize the transaction-with-id to a json formatted string
message = json.dumps(
    token_creation_tx,
    sort_keys=True,
    separators=(',', ':'),
    ensure_ascii=False,
)

# CRYPTO-CONDITIONS: sign the serialized transaction-with-id
ed25519.sign(message.encode(), base58.b58decode(bob.private_key))

# CRYPTO-CONDITIONS: generate the fulfillment uri
fulfillment_uri = ed25519.serialize_uri()

# add the fulfillment uri (signature)
token_creation_tx['inputs'][0]['fulfillment'] = fulfillment_uri

Sending it over to a BigchainDB node:

from bigchaindb_driver import BigchainDB

bdb = BigchainDB('http://bdb-server:9984')
returned_creation_tx = bdb.transactions.send(token_creation_tx)

A few checks:

>>> json.dumps(returned_creation_tx, sort_keys=True) == json.dumps(token_creation_tx, sort_keys=True)
True

>>> token_creation_tx['inputs'][0]['owners_before'][0] == bob.public_key
True

>>> token_creation_tx['outputs'][0]['public_keys'][0] == carly.public_key
True

>>> token_creation_tx['outputs'][0]['amount'] == '10'
True
>>> bdb.transactions.status(creation_txid)
{'status': 'valid'}

Tip

When checking for the status of a transaction, one should keep in mind tiny delays before a transaction reaches a valid status.

Now Carly wants to ride the bicycle for 2 hours so she needs to send 2 tokens to Bob:

# CRYPTO-CONDITIONS: instantiate an Ed25519 crypto-condition for carly
bob_ed25519 = Ed25519Sha256(public_key=base58.b58decode(bob.public_key))

# CRYPTO-CONDITIONS: instantiate an Ed25519 crypto-condition for carly
carly_ed25519 = Ed25519Sha256(public_key=base58.b58decode(carly.public_key))

# CRYPTO-CONDITIONS: generate the condition uris
bob_condition_uri = bob_ed25519.condition.serialize_uri()
carly_condition_uri = carly_ed25519.condition.serialize_uri()

# CRYPTO-CONDITIONS: get the unsigned fulfillment dictionary (details)
bob_unsigned_fulfillment_dict = {
    'type': bob_ed25519.TYPE_NAME,
    'public_key': base58.b58encode(bob_ed25519.public_key),
}
carly_unsigned_fulfillment_dict = {
    'type': carly_ed25519.TYPE_NAME,
    'public_key': base58.b58encode(carly_ed25519.public_key),
}

bob_output = {
    'amount': '2',
    'condition': {
        'details': bob_unsigned_fulfillment_dict,
        'uri': bob_condition_uri,
    },
    'public_keys': (bob.public_key,),
}
carly_output = {
    'amount': '8',
    'condition': {
        'details': carly_unsigned_fulfillment_dict,
        'uri': carly_condition_uri,
    },
    'public_keys': (carly.public_key,),
}

input_ = {
    'fulfillment': None,
    'fulfills': {
        'transaction_id': token_creation_tx['id'],
        'output_index': 0,
    },
    'owners_before': (carly.public_key,)
}

token_transfer_tx = {
    'operation': 'TRANSFER',
    'asset': {'id': token_creation_tx['id']},
    'metadata': None,
    'outputs': (bob_output, carly_output),
    'inputs': (input_,),
    'version': version,
}

# JSON: serialize the id-less transaction to a json formatted string
json_str_tx = json.dumps(
    token_transfer_tx,
    sort_keys=True,
    separators=(',', ':'),
    ensure_ascii=False,
)

# SHA3: hash the serialized id-less transaction to generate the id
transfer_txid = sha3.sha3_256(json_str_tx.encode()).hexdigest()

# add the id
token_transfer_tx['id'] = transfer_txid

# JSON: serialize the transaction-with-id to a json formatted string
message = json.dumps(
    token_transfer_tx,
    sort_keys=True,
    separators=(',', ':'),
    ensure_ascii=False,
)

# CRYPTO-CONDITIONS: sign the serialized transaction-with-id for bob
carly_ed25519.sign(message.encode(), base58.b58decode(carly.private_key))

# CRYPTO-CONDITIONS: generate bob's fulfillment uri
fulfillment_uri = carly_ed25519.serialize_uri()

# add bob's fulfillment uri (signature)
token_transfer_tx['inputs'][0]['fulfillment'] = fulfillment_uri

Sending it over to a BigchainDB node:

bdb = BigchainDB('http://bdb-server:9984')
returned_transfer_tx = bdb.transactions.send(token_transfer_tx)

A few checks:

>>> json.dumps(returned_transfer_tx, sort_keys=True) == json.dumps(token_transfer_tx, sort_keys=True)
True

>>> token_transfer_tx['inputs'][0]['owners_before'][0] == carly.public_key
True
>>> bdb.transactions.status(creation_txid)
{'status': 'valid'}

Tip

When checking for the status of a transaction, one should keep in mind tiny delays before a transaction reaches a valid status.

Multiple Owners Revisited

Walkthrough

We’ll re-use the example of Alice and Bob owning a car together to handcraft transactions with multiple owners.

Say alice and bob own a car together:

In [117]: from bigchaindb_driver.crypto import generate_keypair

In [118]: from bigchaindb_driver import offchain

In [119]: alice, bob = generate_keypair(), generate_keypair()

In [120]: car_asset = {'data': {'car': {'vin': '5YJRE11B781000196'}}}

In [121]: car_creation_tx = offchain.prepare_transaction(
   .....:     operation='CREATE',
   .....:     signers=alice.public_key,
   .....:     recipients=(alice.public_key, bob.public_key),
   .....:     asset=car_asset,
   .....: )
   .....: 

In [122]: signed_car_creation_tx = offchain.fulfill_transaction(
   .....:     car_creation_tx,
   .....:     private_keys=alice.private_key,
   .....: )
   .....: 

In [123]: signed_car_creation_tx
Out[123]: 
{'asset': {'data': {'car': {'vin': '5YJRE11B781000196'}}},
 'id': '26199906bef2e4b48cadf55fb4f5ac5b23d2e24a1d02896e690be2be1ad76211',
 'inputs': [{'fulfillment': 'pGSAIH55KrgklBoqCXfwjGZeDT7PDfeMW31SHVJ9amJuCr0ogUBBvo8hh3I4w8uGaHRUaK7RPWaMguMO5Qtt3ail0GwY-rh2uVXk8lNYiVmaSdFMOooyFw2TkPdsRAL2nOB9qz4K',
   'fulfills': None,
   'owners_before': ['9WhXmeemFs2TSDwLiuWKXTZoGA6xx6gTD9vkaKdTQpHu']}],
 'metadata': None,
 'operation': 'CREATE',
 'outputs': [{'amount': '1',
   'condition': {'details': {'subconditions': [{'public_key': '9WhXmeemFs2TSDwLiuWKXTZoGA6xx6gTD9vkaKdTQpHu',
       'type': 'ed25519-sha-256'},
      {'public_key': '6xGpDm1sVZiLY2NFjzPVCKK61sZnZoGd3FyQcEa7r9fU',
       'type': 'ed25519-sha-256'}],
     'threshold': 2,
     'type': 'threshold-sha-256'},
    'uri': 'ni:///sha-256;Xle8TxbPGEdeUoGKNeqesPDGKE4cbALEUtt7s6p9i5M?fpt=threshold-sha-256&cost=264192&subtypes=ed25519-sha-256'},
   'public_keys': ['9WhXmeemFs2TSDwLiuWKXTZoGA6xx6gTD9vkaKdTQpHu',
    '6xGpDm1sVZiLY2NFjzPVCKK61sZnZoGd3FyQcEa7r9fU']}],
 'version': '1.0'}
sent_car_tx = bdb.transactions.send(signed_car_creation_tx)

One day, alice and bob, having figured out how to teleport themselves, and realizing they no longer need their car, wish to transfer the ownership of their car over to carol:

In [124]: carol = generate_keypair()

In [125]: output_index = 0

In [126]: output = signed_car_creation_tx['outputs'][output_index]

In [127]: input_ = {
   .....:     'fulfillment': output['condition']['details'],
   .....:     'fulfills': {
   .....:         'output_index': output_index,
   .....:         'transaction_id': signed_car_creation_tx['id'],
   .....:     },
   .....:     'owners_before': output['public_keys'],
   .....: }
   .....: 

In [128]: asset = signed_car_creation_tx['id']

In [129]: car_transfer_tx = offchain.prepare_transaction(
   .....:     operation='TRANSFER',
   .....:     recipients=carol.public_key,
   .....:     asset={'id': car_creation_tx['id']},
   .....:     inputs=input_,
   .....: )
   .....: 

In [130]: signed_car_transfer_tx = offchain.fulfill_transaction(
   .....:     car_transfer_tx, private_keys=[alice.private_key, bob.private_key]
   .....: )
   .....: 

In [131]: signed_car_transfer_tx
Out[131]: 
{'asset': {'id': '26199906bef2e4b48cadf55fb4f5ac5b23d2e24a1d02896e690be2be1ad76211'},
 'id': '59a2ae410b055cc9cd6e5d9d36f5ccbfafaff203726fe695de4fb597043df1b1',
 'inputs': [{'fulfillment': 'ooHRoIHMpGSAIFhzQp6l5hofxCT6gE_Fko2my_3V30sa6qG9RrdtQxs_gUAK8MCtJ29pDtKPsd8rKPZ9pSMPqrNCVCRgfY_sj5WmQf0d5aCAivtf3u9_krcr7Hg2sYrfq4ZBnhfHCykdj-0OpGSAIH55KrgklBoqCXfwjGZeDT7PDfeMW31SHVJ9amJuCr0ogUBwTHcUvq73sWvNPe3wdTGFRximLz7VJHnWiuBkoLyN_TvetsFnKckAjsNBmi4TtCbn8Kt4DdZPRGfIroJLD1gDoQA',
   'fulfills': {'output_index': 0,
    'transaction_id': '26199906bef2e4b48cadf55fb4f5ac5b23d2e24a1d02896e690be2be1ad76211'},
   'owners_before': ['9WhXmeemFs2TSDwLiuWKXTZoGA6xx6gTD9vkaKdTQpHu',
    '6xGpDm1sVZiLY2NFjzPVCKK61sZnZoGd3FyQcEa7r9fU']}],
 'metadata': None,
 'operation': 'TRANSFER',
 'outputs': [{'amount': '1',
   'condition': {'details': {'public_key': '4K5KorgB5EXss8gQsUPr9HnrA9QzsnnCM5yieTxMM8aa',
     'type': 'ed25519-sha-256'},
    'uri': 'ni:///sha-256;rq_GZDi8UWOkD7VNkEOmPVMQXomax9Rg_vvZHtlQyPw?fpt=ed25519-sha-256&cost=131072'},
   'public_keys': ['4K5KorgB5EXss8gQsUPr9HnrA9QzsnnCM5yieTxMM8aa']}],
 'version': '1.0'}

Sending the transaction to a BigchainDB node:

sent_car_transfer_tx = bdb.transactions.send(signed_car_transfer_tx)

Doing this manually

In order to do this manually, let’s first import the necessary tools (json, sha3, and cryptoconditions):

In [132]: import json

In [133]: from sha3 import sha3_256

In [134]: from cryptoconditions import Ed25519Sha256, ThresholdSha256

Create the asset, setting all values:

In [135]: car_asset = {
   .....:     'data': {
   .....:         'car': {
   .....:             'vin': '5YJRE11B781000196',
   .....:         },
   .....:     },
   .....: }
   .....: 

Generate the output condition:

In [136]: alice_ed25519 = Ed25519Sha256(public_key=base58.b58decode(alice.public_key))

In [137]: bob_ed25519 = Ed25519Sha256(public_key=base58.b58decode(bob.public_key))

In [138]: threshold_sha256 = ThresholdSha256(threshold=2)

In [139]: threshold_sha256.add_subfulfillment(alice_ed25519)

In [140]: threshold_sha256.add_subfulfillment(bob_ed25519)

In [141]: condition_uri = threshold_sha256.condition.serialize_uri()

In [142]: condition_details = {
   .....:     'subconditions': [
   .....:         {'type': s['body'].TYPE_NAME,
   .....:          'public_key': base58.b58encode(s['body'].public_key)}
   .....:         for s in threshold_sha256.subconditions
   .....:         if (s['type'] == 'fulfillment' and
   .....:             s['body'].TYPE_NAME == 'ed25519-sha-256')
   .....:      ],
   .....:     'threshold': threshold_sha256.threshold,
   .....:     'type': threshold_sha256.TYPE_NAME,
   .....: }
   .....: 

In [143]: output = {
   .....:     'amount': '1',
   .....:     'condition': {
   .....:         'details': condition_details,
   .....:         'uri': condition_uri,
   .....:     },
   .....:     'public_keys': (alice.public_key, bob.public_key),
   .....: }
   .....: 

Tip

The condition uri could have been generated in a slightly different way, which may be more intuitive to you. You can think of the threshold condition containing sub conditions:

In [144]: alt_threshold_sha256 = ThresholdSha256(threshold=2)

In [145]: alt_threshold_sha256.add_subcondition(alice_ed25519.condition)

In [146]: alt_threshold_sha256.add_subcondition(bob_ed25519.condition)

In [147]: alt_threshold_sha256.condition.serialize_uri() == condition_uri
Out[147]: True

The details on the other hand hold the associated fulfillments not yet fulfilled.

The yet to be fulfilled input:

In [148]: input_ = {
   .....:     'fulfillment': None,
   .....:     'fulfills': None,
   .....:     'owners_before': (alice.public_key,),
   .....: }
   .....: 

Craft the payload:

In [149]: version = '1.0'

In [150]: handcrafted_car_creation_tx = {
   .....:     'operation': 'CREATE',
   .....:     'asset': car_asset,
   .....:     'metadata': None,
   .....:     'outputs': (output,),
   .....:     'inputs': (input_,),
   .....:     'version': version,
   .....: }
   .....: 

Generate the id, by hashing the encoded json formatted string representation of the transaction:

In [151]: json_str_tx = json.dumps(
   .....:     handcrafted_car_creation_tx,
   .....:     sort_keys=True,
   .....:     separators=(',', ':'),
   .....:     ensure_ascii=False,
   .....: )
   .....: 

In [152]: car_creation_txid = sha3_256(json_str_tx.encode()).hexdigest()

In [153]: handcrafted_car_creation_tx['id'] = car_creation_txid

Let’s make sure our txid is the same as the one provided by the driver:

In [154]: handcrafted_car_creation_tx['id'] == car_creation_tx['id']
Out[154]: True

Sign the transaction:

In [155]: message = json.dumps(
   .....:     handcrafted_car_creation_tx,
   .....:     sort_keys=True,
   .....:     separators=(',', ':'),
   .....:     ensure_ascii=False,
   .....: )
   .....: 

In [156]: alice_ed25519.sign(message.encode(), base58.b58decode(alice.private_key))
Out[156]: b'A\xbe\x8f!\x87r8\xc3\xcb\x86htTh\xae\xd1=f\x8c\x82\xe3\x0e\xe5\x0bm\xdd\xa8\xa5\xd0l\x18\xfa\xb8v\xb9U\xe4\xf2SX\x89Y\x9aI\xd1L:\x8a2\x17\r\x93\x90\xf7lD\x02\xf6\x9c\xe0}\xab>\n'

In [157]: fulfillment_uri = alice_ed25519.serialize_uri()

In [158]: handcrafted_car_creation_tx['inputs'][0]['fulfillment'] = fulfillment_uri

Compare our signed CREATE transaction with the driver’s:

In [159]: (json.dumps(handcrafted_car_creation_tx, sort_keys=True) ==
   .....:  json.dumps(signed_car_creation_tx, sort_keys=True))
   .....: 
Out[159]: True

The transfer to Carol:

In [160]: alice_ed25519 = Ed25519Sha256(public_key=base58.b58decode(alice.public_key))

In [161]: bob_ed25519 = Ed25519Sha256(public_key=base58.b58decode(bob.public_key))

In [162]: carol_ed25519 = Ed25519Sha256(public_key=base58.b58decode(carol.public_key))

In [163]: unsigned_fulfillments_dict = {
   .....:     'type': carol_ed25519.TYPE_NAME,
   .....:     'public_key': base58.b58encode(carol_ed25519.public_key),
   .....: }
   .....: 

In [164]: condition_uri = carol_ed25519.condition.serialize_uri()

In [165]: output = {
   .....:     'amount': '1',
   .....:     'condition': {
   .....:         'details': unsigned_fulfillments_dict,
   .....:         'uri': condition_uri,
   .....:     },
   .....:     'public_keys': (carol.public_key,),
   .....: }
   .....: 

The yet to be fulfilled input:

In [166]: input_ = {
   .....:     'fulfillment': None,
   .....:     'fulfills': {
   .....:         'transaction_id': handcrafted_car_creation_tx['id'],
   .....:         'output_index': 0,
   .....:     },
   .....:     'owners_before': (alice.public_key, bob.public_key),
   .....: }
   .....: 

Craft the payload:

In [167]: handcrafted_car_transfer_tx = {
   .....:     'operation': 'TRANSFER',
   .....:     'asset': {'id': handcrafted_car_creation_tx['id']},
   .....:     'metadata': None,
   .....:     'outputs': (output,),
   .....:     'inputs': (input_,),
   .....:     'version': version,
   .....: }
   .....: 

Generate the id, by hashing the encoded json formatted string representation of the transaction:

In [168]: json_str_tx = json.dumps(
   .....:     handcrafted_car_transfer_tx,
   .....:     sort_keys=True,
   .....:     separators=(',', ':'),
   .....:     ensure_ascii=False,
   .....: )
   .....: 

In [169]: car_transfer_txid = sha3_256(json_str_tx.encode()).hexdigest()

In [170]: handcrafted_car_transfer_tx['id'] = car_transfer_txid

Let’s make sure our txid is the same as the one provided by the driver:

In [171]: handcrafted_car_transfer_tx['id'] == car_transfer_tx['id']
Out[171]: True

Sign the transaction:

In [172]: message = json.dumps(
   .....:     handcrafted_car_transfer_tx,
   .....:     sort_keys=True,
   .....:     separators=(',', ':'),
   .....:     ensure_ascii=False,
   .....: )
   .....: 

In [173]: threshold_sha256 = ThresholdSha256(threshold=2)

In [174]: alice_ed25519.sign(message=message.encode(),

In [174]: bob_ed25519.sign(message=message.encode(),

In [174]: threshold_sha256.add_subfulfillment(alice_ed25519)

In [174]: threshold_sha256.add_subfulfillment(bob_ed25519)

In [174]: fulfillment_uri = threshold_sha256.serialize_uri()

In [174]: handcrafted_car_transfer_tx['inputs'][0]['fulfillment'] = fulfillment_uri

Compare our signed TRANSFER transaction with the driver’s:

In [174]: (json.dumps(handcrafted_car_transfer_tx, sort_keys=True) ==
   .....:  json.dumps(signed_car_transfer_tx, sort_keys=True))
   .....: 

In a nutshell

Handcrafting the 'CREATE' transaction

import json

import base58
import sha3
from cryptoconditions import Ed25519Sha256, ThresholdSha256

from bigchaindb_driver.crypto import generate_keypair


version = '1.0'

car_asset = {
    'data': {
        'car': {
            'vin': '5YJRE11B781000196',
        },
    },
}

alice, bob = generate_keypair(), generate_keypair()

# CRYPTO-CONDITIONS: instantiate an Ed25519 crypto-condition for alice
alice_ed25519 = Ed25519Sha256(public_key=base58.b58decode(alice.public_key))

# CRYPTO-CONDITIONS: instantiate an Ed25519 crypto-condition for bob
bob_ed25519 = Ed25519Sha256(public_key=base58.b58decode(bob.public_key))

# CRYPTO-CONDITIONS: instantiate a threshold SHA 256 crypto-condition
threshold_sha256 = ThresholdSha256(threshold=2)

# CRYPTO-CONDITIONS: add alice ed25519 to the threshold SHA 256 condition
threshold_sha256.add_subfulfillment(alice_ed25519)

# CRYPTO-CONDITIONS: add bob ed25519 to the threshold SHA 256 condition
threshold_sha256.add_subfulfillment(bob_ed25519)

# CRYPTO-CONDITIONS: generate the condition uri
condition_uri = threshold_sha256.condition.serialize_uri()

# CRYPTO-CONDITIONS: get the unsigned fulfillment dictionary (details)
condition_details = {
    'subconditions': [
        {'type': s['body'].TYPE_NAME,
         'public_key': base58.b58encode(s['body'].public_key)}
        for s in threshold_sha256.subconditions
        if (s['type'] == 'fulfillment' and
            s['body'].TYPE_NAME == 'ed25519-sha-256')
    ],
    'threshold': threshold_sha256.threshold,
    'type': threshold_sha256.TYPE_NAME,
}

output = {
    'amount': '1',
    'condition': {
        'details': condition_details,
        'uri': threshold_sha256.condition_uri,
    },
    'public_keys': (alice.public_key, bob.public_key),
}

# The yet to be fulfilled input:
input_ = {
    'fulfillment': None,
    'fulfills': None,
    'owners_before': (alice.public_key,),
}

# Craft the payload:
handcrafted_car_creation_tx = {
    'operation': 'CREATE',
    'asset': car_asset,
    'metadata': None,
    'outputs': (output,),
    'inputs': (input_,),
    'version': version,
}

# JSON: serialize the id-less transaction to a json formatted string
# Generate the id, by hashing the encoded json formatted string representation of
# the transaction:
json_str_tx = json.dumps(
    handcrafted_car_creation_tx,
    sort_keys=True,
    separators=(',', ':'),
    ensure_ascii=False,
)

# SHA3: hash the serialized id-less transaction to generate the id
car_creation_txid = sha3.sha3_256(json_str_tx.encode()).hexdigest()

# add the id
handcrafted_car_creation_tx['id'] = car_creation_txid

# JSON: serialize the transaction-with-id to a json formatted string
message = json.dumps(
    handcrafted_car_creation_tx,
    sort_keys=True,
    separators=(',', ':'),
    ensure_ascii=False,
)

# CRYPTO-CONDITIONS: sign the serialized transaction-with-id
alice_ed25519.sign(message.encode(), base58.b58decode(alice.private_key))

# CRYPTO-CONDITIONS: generate the fulfillment uri
fulfillment_uri = alice_ed25519.serialize_uri()

# add the fulfillment uri (signature)
handcrafted_car_creation_tx['inputs'][0]['fulfillment'] = fulfillment_uri

Sending it over to a BigchainDB node:

from bigchaindb_driver import BigchainDB

bdb = BigchainDB('http://bdb-server:9984')
returned_car_creation_tx = bdb.transactions.send(handcrafted_car_creation_tx)

Wait for some nano seconds, and check the status:

>>> bdb.transactions.status(returned_car_creation_tx['id'])
{'status': 'valid'}

Handcrafting the 'TRANSFER' transaction

version = '1.0'

carol = generate_keypair()

alice_ed25519 = Ed25519Sha256(public_key=base58.b58decode(alice.public_key))

bob_ed25519 = Ed25519Sha256(public_key=base58.b58decode(bob.public_key))

carol_ed25519 = Ed25519Sha256(public_key=base58.b58decode(carol.public_key))

unsigned_fulfillments_dict = {
    'type': carol_ed25519.TYPE_NAME,
    'public_key': base58.b58encode(carol_ed25519.public_key),
}

condition_uri = carol_ed25519.condition.serialize_uri()

output = {
    'amount': '1',
    'condition': {
        'details': unsigned_fulfillments_dict,
        'uri': condition_uri,
    },
    'public_keys': (carol.public_key,),
}

# The yet to be fulfilled input:
input_ = {
    'fulfillment': None,
    'fulfills': {
        'transaction_id': handcrafted_car_creation_tx['id'],
        'output_index': 0,
    },
    'owners_before': (alice.public_key, bob.public_key),
}

# Craft the payload:
handcrafted_car_transfer_tx = {
    'operation': 'TRANSFER',
    'asset': {'id': handcrafted_car_creation_tx['id']},
    'metadata': None,
    'outputs': (output,),
    'inputs': (input_,),
    'version': version,
}

# Generate the id, by hashing the encoded json formatted string
# representation of the transaction:
json_str_tx = json.dumps(
    handcrafted_car_transfer_tx,
    sort_keys=True,
    separators=(',', ':'),
    ensure_ascii=False,
)

car_transfer_txid = sha3.sha3_256(json_str_tx.encode()).hexdigest()

handcrafted_car_transfer_tx['id'] = car_transfer_txid

# Sign the transaction:
message = json.dumps(
    handcrafted_car_transfer_tx,
    sort_keys=True,
    separators=(',', ':'),
    ensure_ascii=False,
)

threshold_sha256 = ThresholdSha256(threshold=2)

alice_ed25519.sign(message=message.encode(),
                   private_key=base58.b58decode(alice.private_key))
bob_ed25519.sign(message=message.encode(),
                 private_key=base58.b58decode(bob.private_key))

threshold_sha256.add_subfulfillment(alice_ed25519)

threshold_sha256.add_subfulfillment(bob_ed25519)

fulfillment_uri = threshold_sha256.serialize_uri()

handcrafted_car_transfer_tx['inputs'][0]['fulfillment'] = fulfillment_uri

Sending it over to a BigchainDB node:

bdb = BigchainDB('http://bdb-server:9984')
returned_car_transfer_tx = bdb.transactions.send(handcrafted_car_transfer_tx)

Wait for some nano seconds, and check the status:

>>> bdb.transactions.status(returned_car_transfer_tx['id'])
{'status': 'valid'}

Multiple Owners with m-of-n Signatures

In this example, alice and bob co-own a car asset such that only one of them is required to sign the transfer transaction. The example is very similar to the one where both owners are required to sign, but with minor differences that are very important, in order to make the fulfillment URI valid.

We only show the “nutshell” version for now. The example is self-contained.

In a nutshell

Handcrafting the 'CREATE' transaction

import json

import base58
import sha3
from cryptoconditions import Ed25519Sha256, ThresholdSha256

from bigchaindb_driver.crypto import generate_keypair


version = '1.0'

car_asset = {
    'data': {
        'car': {
            'vin': '5YJRE11B781000196',
        },
    },
}

alice, bob = generate_keypair(), generate_keypair()

# CRYPTO-CONDITIONS: instantiate an Ed25519 crypto-condition for alice
alice_ed25519 = Ed25519Sha256(public_key=base58.b58decode(alice.public_key))

# CRYPTO-CONDITIONS: instantiate an Ed25519 crypto-condition for bob
bob_ed25519 = Ed25519Sha256(public_key=base58.b58decode(bob.public_key))

# CRYPTO-CONDITIONS: instantiate a threshold SHA 256 crypto-condition
# NOTICE that the threshold is set to 1, not 2
threshold_sha256 = ThresholdSha256(threshold=1)

# CRYPTO-CONDITIONS: add alice ed25519 to the threshold SHA 256 condition
threshold_sha256.add_subfulfillment(alice_ed25519)

# CRYPTO-CONDITIONS: add bob ed25519 to the threshold SHA 256 condition
threshold_sha256.add_subfulfillment(bob_ed25519)

# CRYPTO-CONDITIONS: generate the condition uri
condition_uri = threshold_sha256.condition.serialize_uri()

# CRYPTO-CONDITIONS: get the unsigned fulfillment dictionary (details)
condition_details = {
    'subconditions': [
        {'type': s['body'].TYPE_NAME,
         'public_key': base58.b58encode(s['body'].public_key)}
        for s in threshold_sha256.subconditions
        if (s['type'] == 'fulfillment' and
            s['body'].TYPE_NAME == 'ed25519-sha-256')
    ],
    'threshold': threshold_sha256.threshold,
    'type': threshold_sha256.TYPE_NAME,
}

output = {
    'amount': '1',
    'condition': {
        'details': condition_details,
        'uri': threshold_sha256.condition_uri,
    },
    'public_keys': (alice.public_key, bob.public_key),
}

# The yet to be fulfilled input:
input_ = {
    'fulfillment': None,
    'fulfills': None,
    'owners_before': (alice.public_key,),
}

# Craft the payload:
handcrafted_car_creation_tx = {
    'operation': 'CREATE',
    'asset': car_asset,
    'metadata': None,
    'outputs': (output,),
    'inputs': (input_,),
    'version': version,
}

# JSON: serialize the id-less transaction to a json formatted string
# Generate the id, by hashing the encoded json formatted string representation of
# the transaction:
json_str_tx = json.dumps(
    handcrafted_car_creation_tx,
    sort_keys=True,
    separators=(',', ':'),
    ensure_ascii=False,
)

# SHA3: hash the serialized id-less transaction to generate the id
car_creation_txid = sha3.sha3_256(json_str_tx.encode()).hexdigest()

# add the id
handcrafted_car_creation_tx['id'] = car_creation_txid

# JSON: serialize the transaction-with-id to a json formatted string
message = json.dumps(
    handcrafted_car_creation_tx,
    sort_keys=True,
    separators=(',', ':'),
    ensure_ascii=False,
)

# CRYPTO-CONDITIONS: sign the serialized transaction-with-id
alice_ed25519.sign(message.encode(), base58.b58decode(alice.private_key))

# CRYPTO-CONDITIONS: generate the fulfillment uri
fulfillment_uri = alice_ed25519.serialize_uri()

# add the fulfillment uri (signature)
handcrafted_car_creation_tx['inputs'][0]['fulfillment'] = fulfillment_uri

Sending it over to a BigchainDB node:

from bigchaindb_driver import BigchainDB

bdb = BigchainDB('http://bdb-server:9984')
returned_car_creation_tx = bdb.transactions.send(handcrafted_car_creation_tx)

Wait for some nano seconds, and check the status:

>>> bdb.transactions.status(returned_car_creation_tx['id'])
 {'status': 'valid'}

Handcrafting the 'TRANSFER' transaction

version = '1.0'

carol = generate_keypair()

alice_ed25519 = Ed25519Sha256(public_key=base58.b58decode(alice.public_key))

bob_ed25519 = Ed25519Sha256(public_key=base58.b58decode(bob.public_key))

carol_ed25519 = Ed25519Sha256(public_key=base58.b58decode(carol.public_key))

condition_uri = carol_ed25519.condition.serialize_uri()

output = {
    'amount': '1',
    'condition': {
        'details': {
            'type': carol_ed25519.TYPE_NAME,
            'public_key': base58.b58encode(carol_ed25519.public_key),
        },
        'uri': condition_uri,
    },
    'public_keys': (carol.public_key,),
}

# The yet to be fulfilled input:
input_ = {
    'fulfillment': None,
    'fulfills': {
        'transaction_id': handcrafted_car_creation_tx['id'],
        'output_index': 0,
    },
    'owners_before': (alice.public_key, bob.public_key),
}

# Craft the payload:
handcrafted_car_transfer_tx = {
    'operation': 'TRANSFER',
    'asset': {'id': handcrafted_car_creation_tx['id']},
    'metadata': None,
    'outputs': (output,),
    'inputs': (input_,),
    'version': version,
}

# Generate the id, by hashing the encoded json formatted string
# representation of the transaction:
json_str_tx = json.dumps(
    handcrafted_car_transfer_tx,
    sort_keys=True,
    separators=(',', ':'),
    ensure_ascii=False,
)

car_transfer_txid = sha3.sha3_256(json_str_tx.encode()).hexdigest()

handcrafted_car_transfer_tx['id'] = car_transfer_txid

# Sign the transaction:
message = json.dumps(
    handcrafted_car_transfer_tx,
    sort_keys=True,
    separators=(',', ':'),
    ensure_ascii=False,
)

threshold_sha256 = ThresholdSha256(threshold=1)

alice_ed25519.sign(message.encode(),
                   private_key=base58.b58decode(alice.private_key))

threshold_sha256.add_subfulfillment(alice_ed25519)

threshold_sha256.add_subcondition(bob_ed25519.condition)

fulfillment_uri = threshold_sha256.serialize_uri()

handcrafted_car_transfer_tx['inputs'][0]['fulfillment'] = fulfillment_uri

Sending it over to a BigchainDB node:

bdb = BigchainDB('http://bdb-server:9984')
returned_car_transfer_tx = bdb.transactions.send(handcrafted_car_transfer_tx)

Wait for some nano seconds, and check the status:

>>> bdb.transactions.status(returned_car_transfer_tx['id'])
 {'status': 'valid'}