Comments (3)
Here we go... Hand crafted Hash-Locked ...
import hashlib
import json
import time
from bigchaindb_driver import BigchainDB
import cryptoconditions as cc
from cryptoconditions.crypto import Ed25519SigningKey as SigningKey
Create Transaction
class CreateTxnManager():
def __init__(self, params):
self.bigchaindb_url = 'http://172.16.217.94:9984'
self.b = self.getChainDriver()
self.condition = ''
self.owner_pub_key = params.get('owner_public_key')
self.owner_priv_key = params.get('owner_private_key')
self.requester_pub_key = params.get('requester_publickey')
def getChainDriver(self):
return BigchainDB(self.bigchaindb_url)
def txInput(self):
input_ = {
'fulfillment': None,
'fulfills': None,
'owners_before': (self.owner_pub_key,)
}
return input_
def txOutput(self):
secret = str.encode(self.secret_message)
tx_condition = cc.PreimageSha256Fulfillment(preimage=secret)
self.condition = tx_condition
output = {
'amount': 1,
'condition': {
'details': tx_condition.to_dict(),
'uri': tx_condition.condition_uri,
},
'public_keys': (self.owner_pub_key,),
}
return output
def tx_prepare(self, assets):
return {
'operation': 'CREATE',
'asset': {
'data': assets
},
'metadata': None,
'outputs': (self.txOutput(),),
'inputs': (self.txInput(),),
'version': '0.9',
}
def createAsset(self, params, assets):
key = str(time.time())
self.secret_message = hashlib.sha3_256(key.encode()).hexdigest()
return self.deployAsset(assets)
def deployAsset(self, assets):
tx = self.tx_prepare(assets)
json_str_tx = json.dumps(
tx,
sort_keys=True,
separators=(',', ':'),
ensure_ascii=False,
)
creation_txid = hashlib.sha3_256(json_str_tx.encode()).hexdigest()
tx['id'] = creation_txid
fl_str_tx = json.dumps(
tx,
sort_keys=True,
separators=(',', ':'),
ensure_ascii=False,
)
tx['inputs'][0]['fulfillment'] = self.condition.serialize_uri()
returned_creation_tx = self.b.transactions.send(tx)
if self.validateTx(tx['id']) == 'valid':
return {'status':'True', "token": self.secret_message, "create_txn_id": tx['id'] }
else:
return {'status':'False'}
def validateTx(self, txid):
trails = 0
while trails < 100:
try:
if self.b.transactions.status(txid).get('status') == 'valid':
break
except bigchaindb_driver.exceptions.NotFoundError:
trails += 1
return self.b.transactions.status(txid).get('status')
Transfer txn
class TranferTxManager():
# token : secret_token
def __init__(self, token):
self.bigchaindb_url = 'http://172.16.217.94:9984'
self.b = self.getChainDriver()
self.preimage = token
def getChainDriver(self):
return BigchainDB(self.bigchaindb_url)
def validateTx(self, txid):
trails = 0
while trails < 100:
try:
if self.b.transactions.status(txid).get('status') == 'valid':
break
except bigchaindb_driver.exceptions.NotFoundError:
trails += 1
return self.b.transactions.status(txid).get('status')
"""
data = {
'txnId': <Create TXN ID>,
'pubkey': "<requester pub key>"
}
"""
def trasferAsset(self, data):
data = self.getTxnDetails()
if data and data.get('txId'):
if self.validateTx(data.get('txId')) == 'valid':
return self.prepareAssetTransfer(data)
else:
return {"status":"False", "error": "invalid create transaction"}
return {"status":"False", "error": "invalid attempt"}
def transferInput(self, tx):
index = 0
output = tx['outputs'][index]
input_ = {
'fulfillment': output['condition']['details'],
'fulfills': {
'output': index,
'txid': tx['id'],
},
'owners_before': output['public_keys'],
}
return input_
def prepareAssetTransfer(self, data):
txnid = data.get('txId')
tx = self.b.transactions.retrieve(txnid)
transferAsset = {
'id': tx['id']
}
transferTx = self.b.transactions.prepare(
operation='TRANSFER',
recipients=data.get('pubkey'),
asset=transferAsset,
inputs=self.transferInput(tx),
)
transfer_tx_condition = cc.PreimageSha256Fulfillment(preimage=str.encode(self.preimage))
if tx['inputs'][0]['fulfillment'] == transfer_tx_condition.serialize_uri():
transferTx['inputs'][0]['fulfillment'] = transfer_tx_condition.serialize_uri()
sent_transfer_tx = self.b.transactions.send(transferTx)
return {"status":"True", "asset":tx['asset']['data']}
else:
return {"status":"False", "error": "invalid transaction id"}
from bigchaindb-driver.
Hi @arunkumarsekar! Sorry for not getting back to you earlier. Thanks for sharing your solution! We will look into how we can integrate it soon.
from bigchaindb-driver.
What happened with this? The Docs lead here in a Todo box.
Is the above solution functional at present?
from bigchaindb-driver.
Related Issues (20)
- gcc: error: unrecognized command line option '-fstack-clash-protection' HOT 5
- Cap exponential backoff delay
- Problem: All recent builds of the Python driver docs are failing on ReadTheDocs HOT 3
- send() is deprecated, remove it for the next release
- TimeoutError when commit sending transactions HOT 2
- Server installation and setup issue? HOT 1
- name ‘signed_tx’ is not defined
- Error on broadcastTxCommit: EOF HOT 8
- throw an error in send_commit() HOT 6
- Unable to install driver on 64 bit windows and python 3.7 HOT 3
- Getting error while sending transaction over bigchaindb node HOT 2
- after transfer the asset has no data
- Curl success, but Internal Server Error when commit transaction HOT 3
- Adding new (person) public key in transfer function recipient, Invalid transaction (InvalidSignature): Transaction signature is invalid.","status":400
- Django -No module named 'bigchaindb_driver' HOT 2
- How to install the driver in conda HOT 1
- Unable to install bigchaindb-driver package from pip HOT 2
- Workaround to use the driver with bigchaindb behind https NGINX
- keep getting errors for not being able to build wheels for python-rapidjson, cryptography, PyNaCl HOT 4
- remove pysha3?
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from bigchaindb-driver.