def send(args, peer, tx): # Stop sending transactions if unconfirmed # transaction in mempool are above the set # threshold TM_HTTP_ENDPOINT = 'http://{}:26657'.format(urlparse(peer).hostname) unconfirmed_tx_th = args.unconfirmed_tx_th unconfirmed_txs = get_unconfirmed_tx(TM_HTTP_ENDPOINT) backoff_time = 1 while unconfirmed_txs > unconfirmed_tx_th: sleep(backoff_time) unconfirmed_txs = get_unconfirmed_tx(TM_HTTP_ENDPOINT) driver = BigchainDB(peer, headers=args.auth) ts_send = ts() ts_error = None ts_accept = None try: driver.transactions.send(tx, mode=args.mode) except TransportError: ts_error = ts() else: ts_accept = ts() return peer, tx['id'], len(dumps(tx)), ts_send, ts_accept, ts_error
def __init__(self, connection_url, headers=None): headers = headers or {} self.connection_url = connection_url self.driver = BigchainDB(connection_url, headers=headers) self.app_id = headers.get('app_id', '') self.models = OrmModels()
def showAppendResult(): if request.method == "POST": tx_id = request.form["tx_id"] nik_id = request.form["nik_id"], nama = request.form["nama"], ttl = request.form["ttl"], alamat = request.form["alamat"], gejala = request.form["gejala"], comment = request.form["comment"] patient_asset = { 'data' : { 'patient' : { 'nik_id' : nik_id, 'nama' : nama, 'ttl' : ttl, 'alamat' : alamat, 'gejala' : gejala, 'comment' : comment } } } bdb_root_url = 'http://34.101.231.183:9984/' bdb = BigchainDB(bdb_root_url) tx = transfer_medical_data(bdb, tx_id,patient_asset) return render_template("append-result.html",content=tx) else: return redirect(url_for("showSearchPage"))
def cli(config): """ LIFTOFF interface to blockchain. """ global bdb_cfg, config_file, bdb config_file = config bdb_cfg = yaml.load(open(config, 'r')) bdb = BigchainDB(bdb_cfg['bigchaindb']['url'], headers=bdb_cfg['headers'])
def closure(use_canonical_key=None): bdb = BigchainDB() if use_canonical_key: alice = SimpleNamespace( private_key=b58encode(use_canonical_key[0]).decode(), public_key=b58encode(use_canonical_key[1][1:]).decode()) else: alice = generate_keypair() prepared_creation_tx = bdb.transactions.prepare( operation='CREATE', signers=alice.public_key, asset={ 'data': { 'bicycle': { 'serial_number': ''.join(random.sample(string.hexdigits, 20)), 'manufacturer': 'bkfab', }, }, }, metadata={'planet': 'earth'}, ) fulfilled_creation_tx = bdb.transactions.fulfill( prepared_creation_tx, private_keys=alice.private_key) return fulfilled_creation_tx
def search_data(): _result_msg = "done" _datalist = [] _jsonData = request.get_json() user_agent = request.headers.get('User-Agent', "") if type(_jsonData) is str: _jsonData = json.loads(request.get_json()) _keywords = _jsonData['keywords'] _limit = 0 if "limit" in _jsonData: _limit = _jsonData['limit'] try: bdb = BigchainDB(setting.blockchain_db_url) _datalist = bdb.assets.get(search=_keywords, limit=_limit) _result_msg = "search data is done." except Exception as e: _result_msg = e _resultDict = dict(msg=("%s") % (_result_msg), datalist=_datalist) return _resultDict
def get_data(): _result_msg = "done" _blockdata = "" _jsonData = request.get_json() user_agent = request.headers.get('User-Agent', "") if type(_jsonData) is str: _jsonData = json.loads(request.get_json()) _blockid = _jsonData['blockid'] try: bdb = BigchainDB(setting.blockchain_db_url) _assertdata = bdb.assets.get(search=_blockid) if len(_assertdata) > 0: if "data" in _assertdata[0]: _blockdata = _assertdata[0]["data"]["blockdata"] _result_msg = "find data done!" else: _result_msg = "don't have data !" else: _result_msg = "don't find blockid data !" except Exception as e: _result_msg = e _resultDict = dict(msg=("%s") % (_result_msg), data=_blockdata) return _resultDict
def get_connection(): with open(CONFIG_FILE_PATH) as f: data = dict(json.load(f)) print("connecting to ", data[HOST]) bdb = BigchainDB(data[HOST]) return bdb
def create_course(request): form = CreateCourseForm(request.POST) if request.method == "POST" and form.validate(): bdb = BigchainDB(request.registry.settings['bigchaindb.url']) course_asset = { 'data': { 'course': { 'appname': 'BlockchainGolfers', 'assetclass': 'BGA_GolfCourse', 'coursename': form.coursename.data, 'courselocation': form.courselocation.data } } } course_metadata = { 'rating': str(form.rating.data), 'slope': str(form.slope.data), 'courseimage': str(form.courseimage.data) } user = UserService.by_name(request.authenticated_userid, request=request) prepared_creation_tx = bdb.transactions.prepare( operation='CREATE', signers=user.pubkey, asset=course_asset, metadata=course_metadata) fulfilled_creation_tx = bdb.transactions.fulfill( prepared_creation_tx, private_keys=user.privkey) sent_creation_tx = bdb.transactions.send_commit(fulfilled_creation_tx) return HTTPFound(location=request.route_url('createcourse')) return {'form': form, 'user': request.authenticated_userid}
def main(): # Conecta ao nó de teste do BigchainDB bdb = BigchainDB('https://test.bigchaindb.com') # Gera o par de chaves para o sistema gravar as informações no banco de dados Blockchain evoting = generate_keypair() eleitores = get_eleitores() votos_computados = [] for i in range(0, len(eleitores) - 1): voto = bdb.transactions.prepare(operation='CREATE', signers=evoting.public_key, asset={ 'data': { 'id': eleitores[i]['id'], 'nome': eleitores[i]['nome'], 'voto': eleitores[i]['voto'] } }) voto_assinado = bdb.transactions.fulfill( voto, private_keys=evoting.private_key) voto_enviado = bdb.transactions.send_commit(voto_assinado) votos_computados.append(voto_enviado) # Imprime as informações gravadas no banco de dados Blockchain print(json.dumps(votos_computados, sort_keys=True, indent=4))
def main(): bdb_root_url = 'http://34.101.231.183:9984/' bdb = BigchainDB(bdb_root_url) alice = generate_keypair() bob = generate_keypair() # contoh asset data untuk block id_number = input("Masukkan nomor nomor id: ") patient_name = input("Masukkan nama pasien: ") symptoms = input("Masukkan gejala: ") division = input("Masukkan divisi RS: ") medication = input("Masukkan resep obat: ") comment = input("(Opsional) Masukkan Komentar: ") patient_data = { 'data': { 'patient': { 'id_number': id_number, 'patient_name': patient_name, 'symptoms': symptoms, 'division': division, 'medication': medication }, }, } # contoh metadata untuk asset block metadata = {'comment': comment} create_transaction(bdb, patient_data, metadata, alice)
class Query(Resource): BDB = BigchainDB(settings['bigchainurl']) # TODO: add jwt auth to this # @jwt_required() def get(self): parser = reqparse.RequestParser() parser.add_argument('alias') params = parser.parse_args() if len(Query.BDB.metadata.get(search=params['alias'])) > 0: return {'alias': Query.BDB.metadata.get(params['alias'])}, 200 else: return {'result': "No results found"}, 404 def post(self): # TODO: create a test payload and use postman to test if it accepts signed transactions try: parser = reqparse.RequestParser() parser.add_argument('signed_transaction') params = parser.parse_args() transaction_id = Query.BDB.transactions.send_commit( params['signed_transaction']) return {'transaction_id': transaction_id['metadata']}, 201 except ValueError: return {'result': "Value error"}, 400 except InvalidAliasException: return {'result': "Alias already exists!"}, 400
def test_cli_import(random_fulfilled_tx_gen, click_runner, session_tx_cache_obj, default_password, tmp_home): bdb = BigchainDB('test.ipdb.io') xkey = seed_to_extended_key(os.urandom(64)) transactions = {} for account in range(3): for index in range(3): dxk = bdbw_derive_account(xkey, account=account, index=index) ftx = random_fulfilled_tx_gen( use_canonical_key=(dxk.privkey, privkey_to_pubkey(dxk.privkey))) result = bdb.transactions.send_commit(ftx) transactions[result['id']] = result result = click_runner.invoke(cli.import_, [ "key", xkey.privkey.hex(), xkey.chaincode.hex(), "--password", default_password, "--url", "test.ipdb.io", "--force" ]) session_tx_cache_obj._loaddb() # Reload file for id_, tx in transactions.items(): assert session_tx_cache_obj.get(id_) == tx
def __init__(self, ip_address, test=False): self.routes = {} # dst_ip: next_hop_ip self.sockets = {} # next_hop_ip: socket_instance self.keys = {} # ip: packet_public_key self.sqn_numbers = {} # ip: most recent sequence number received self.neighbors = set() # ip addresses of neighbors self.hosts = [] # any hosts attached to this router self.buffer_lock = Lock() self.socket_lock = Lock() self.sqn_lock = Lock() self.sqn_counter = 0 # For unit tests self.test = test # Key used for signing packets self.packet_key = RSA.generate(2048) self.keys[ip_address] = self.packet_key.publickey() # Connect to bigchaindb if not test: bdb_root_url = 'http://localhost:9984' # TODO: is this right? self.bdb = BigchainDB(bdb_root_url) # Read bdb keypair from the .bigchaindb config file with open('build/.bigchaindb') as f: d = json.load(f) self.bdb_keypair = CryptoKeypair( d['keypair']['private'], d['keypair']['public'], ) self.keyring = d['keyring'] print('My key:') print(self.packet_key.publickey().export_key().decode()) # Add packet public key, IP addr to bigchaindb asset = { 'data': { 'public_key': self.packet_key.publickey().export_key().decode(), 'ip_address': ip_address, }, } prepared_transaction = self.bdb.transactions.prepare( operation='CREATE', signers=self.bdb_keypair.public_key, asset=asset, ) fulfilled_transaction = self.bdb.transactions.fulfill( prepared_transaction, private_keys=self.bdb_keypair.private_key, ) sent_txn = self.bdb.transactions.send(fulfilled_transaction) self.socket = socket.socket() self.socket.bind((ip_address, ROUTER_PORT)) self.socket.listen() self.ip_address = ip_address print("starting server on {0}:{1}".format(ip_address, ROUTER_PORT))
def test_double_create(): bdb = BigchainDB(os.environ.get('BIGCHAINDB_ENDPOINT')) alice = generate_keypair() results = queue.Queue() tx = bdb.transactions.fulfill( bdb.transactions.prepare( operation='CREATE', signers=alice.public_key, asset={'data': {'uuid': str(uuid4())}}), private_keys=alice.private_key) def send_and_queue(tx): try: bdb.transactions.send(tx) results.put('OK') except bigchaindb_driver.exceptions.TransportError as e: results.put('FAIL') t1 = Thread(target=send_and_queue, args=(tx, )) t2 = Thread(target=send_and_queue, args=(tx, )) t1.start() t2.start() results = [results.get(timeout=2), results.get(timeout=2)] assert results.count('OK') == 1 assert results.count('FAIL') == 1
def resolve_transactions(self, args, context, info): bdb = BigchainDB() asset_id = args.get('asset_id') operation = args.get('operation', None) retrieved_txs = bdb.transactions.get(asset_id=asset_id, operation=operation) return [TransactionType.from_json(tx) for tx in retrieved_txs]
def add_block(data): bdb_root_url = 'https://test.bigchaindb.com' bdb = BigchainDB(bdb_root_url) alice = generate_keypair() # data = {'data': # {'123abc': # { # 'question': '1', # 'text': 'bkfabdcfreferfejfbewjuhcbwdichbewidyewbdiew ieydvewudhew eduew utvewboiugy ewduie', # 'marks': 0.35, # }, # }, # } prepared_creation_tx = bdb.transactions.prepare( operation='CREATE', signers=alice.public_key, asset=data, ) fulfilled_creation_tx = bdb.transactions.fulfill( prepared_creation_tx, private_keys=alice.private_key) sent_creation_tx = bdb.transactions.send_commit(fulfilled_creation_tx) block_height = bdb.blocks.get(txid=sent_creation_tx['id']) block = bdb.blocks.retrieve(str(block_height)) # print() print(block['transactions'][0].get('asset').get('data'))
def __init__(self): tokens = {} tokens['app_id'] = '764af86d' tokens['app_key'] = 'e416ddf812ab8b6196bc772280e7bea5' self.bdb = BigchainDB('https://test.ipdb.io', headers=tokens) self.alice = generate_keypair() self.bob = generate_keypair()
def __init__(self): self.admin = None # port to which connect to self.db = BigchainDB('192.168.99.100:9984') self.nameSpace = 'testament' # id of the application self.app_id = None self.admin_grp_id = None
def queryer(srch): from bigchaindb_driver import BigchainDB bdb = BigchainDB('https://test.ipdb.io/') msg = bdb.assets.get(search=srch) if msg == []: return "Not Found" return msg
def cli(config): """ LIFTOFF interface to blockchain. """ global bdb_cfg, config_file, bdb load_cfg (config) bdb = BigchainDB( bdb_cfg['bigchaindb']['url'], headers=bdb_cfg['headers'])
def __init__(self, bdb_server_url, sharge=None, mobile=None): self.bdb = BigchainDB(bdb_server_url) self.sharge = sharge self.mobile = mobile self.data_stream = [] self.create_stream()
def __init__(self, bigchaindb_endpoint=_DEFAULT_BIGCHAINDB_ENDPOINT, mongo_endpoint=_DEFAULT_MONGO_ENDPOINT, credential=generate_keypair()): self.bdb = BigchainDB(bigchaindb_endpoint) self.mdb = MongoClient(mongo_endpoint)['bigchain'] self.key = credential self.transaction_history = []
def from_json(cls, fulfills): bdb = BigchainDB() try: retrieved_tx = bdb.transactions.retrieve( fulfills['transaction_id']) return cls(output_index=fulfills['output_index'], transaction=TransactionType.from_json(retrieved_tx)) except (KeyError, TypeError, NotFoundError): return cls(output_index=None, transaction=None)
def __init__(self, app=None): self.bigchain = BigchainDB(BaseConfig.BIGCHAINDB__URL) keypair = generate_keypair() print('keypair', keypair) self.logger = None if app: self.init_app(app)
def courses(request): bdb = BigchainDB(request.registry.settings['bigchaindb.url']) courses = bdb.assets.get(search='BGA_GolfCourse') course_list = [] for course in courses: courses_meta = bdb.metadata.get(search=course['id']) course.update(courses_meta[0]) course_list.append(course) return {'courses': course_list, 'user': request.authenticated_userid}
def showAppendForm(): if request.method == "POST": tx_id = request.form["tx_id"] bdb_root_url = 'http://34.101.231.183:9984/' bdb = BigchainDB(bdb_root_url) tx = retrieve_medical_data(bdb,tx_id) return render_template("append-form.html",content=tx, tx_id = tx_id) else: return redirect(url_for("showSearchPage"))
def init_system(self, bdb_ip, bdb_port, pub_key, pr_key): self.bdb = BigchainDB('http://{0}:{1}'.format(bdb_ip, bdb_port)) self.keypair = {'private_key': pr_key, 'public_key': pub_key} self.asset_data = { 'data': { 'asset_class': 'vehicle_telemetry', 'asset_author': 'hackfest-berlin-2017-team' } } self.txids = {}
def __init__(self, config=None): scheme = get_value('db.scheme', 'DB_SCHEME', 'http', config) host = get_value('db.hostname', 'DB_HOSTNAME', 'localhost', config) port = int(get_value('db.port', 'DB_PORT', 9984, config)) app_id = get_value('db.app_id', 'DB_APP_ID', None, config) app_key = get_value('db.app_key', 'DB_APP_KEY', None, config) bdb_root_url = '%s://%s:%s' % (scheme, host, port) tokens = {'app_id': app_id, 'app_key': app_key} self._bdb = BigchainDB(bdb_root_url, headers=tokens)
def checker(id): from bigchaindb_driver import BigchainDB bdb = BigchainDB('https://test.ipdb.io/') block_height = bdb.blocks.get(txid=id) try: if bdb.blocks.retrieve(str(block_height)): return "sucess" except: return "failed or incorrect ID"