High-level API call (meant to be blockchain-agnostic)
    What is the fee for the transaction?
435295
def calculate_tx_fee( tx_hex, fee_per_byte ):
    
    txobj = btc_tx_deserialize(tx_hex)
    tx_num_bytes = len(tx_hex) / 2
    num_virtual_bytes = None

    if btc_tx_is_segwit(tx_hex):
        # segwit--discount witness data 
        witness_len = 0
        for inp in txobj['ins']:
            witness_len += len(inp['witness_script']) / 2 

        # see https://bitcoincore.org/en/segwit_wallet_dev/#transaction-fee-estimation
        tx_num_bytes_original = tx_num_bytes - witness_len
        num_virtual_bytes = 3 * tx_num_bytes_original + tx_num_bytes

    else:
        # non-segwit 
        num_virtual_bytes = tx_num_bytes * 4

    return (fee_per_byte * num_virtual_bytes) / 4
375824
def get_hex(self, signed=True):
        
        total_ins_satoshi = self.total_input_satoshis()
        if total_ins_satoshi == 0:
            raise ValueError("Can't make transaction, there are zero inputs")

        # Note: there can be zero outs (sweep or coalesc transactions)
        total_outs_satoshi = sum([x['value'] for x in self.outs])

        if not self.fee_satoshi:
            self.fee() # use default of $0.02

        change_satoshi = total_ins_satoshi - (total_outs_satoshi + self.fee_satoshi)

        if change_satoshi < 0:
            raise ValueError(
                "Input amount (%s) must be more than all output amounts (%s) plus fees (%s). You need more %s."
                % (total_ins_satoshi, total_outs_satoshi, self.fee_satoshi, self.crypto.upper())
            )

        ins = [x['input'] for x in self.ins]

        if change_satoshi > 0:
            if self.verbose:
                print("Adding change address of %s satoshis to %s" % (change_satoshi, self.change_address))
            change = [{'value': change_satoshi, 'address': self.change_address}]
        else:
            change = [] # no change ?!
            if self.verbose: print("Inputs == Outputs, no change address needed.")

        tx = mktx(ins, self.outs + change)

        if signed:
            for i, input_data in enumerate(self.ins):
                if not input_data['private_key']:
                    raise Exception("Can't sign transaction, missing private key for input %s" % i)
                tx = sign(tx, i, input_data['private_key'])

        return tx
428755
def create_unsigned_transaction(cls,
                                    *,
                                    nonce: int,
                                    gas_price: int,
                                    gas: int,
                                    to: Address,
                                    value: int,
                                    data: bytes) -> 'BaseUnsignedTransaction':
        
        return cls.get_transaction_class().create_unsigned_transaction(
            nonce=nonce,
            gas_price=gas_price,
            gas=gas,
            to=to,
            value=value,
            data=data
        )
1050727
async def put(self, public_key):
		
		if settings.SIGNATURE_VERIFICATION:
			super().verify()

		# Check if message contains required data
		try:
			body = json.loads(self.request.body)
		except:
			self.set_status(400)
			self.write({"error":400, "reason":"Unexpected data format. JSON required"})
			raise tornado.web.Finish
			
		if isinstance(body["message"], str):
			message = json.loads(body["message"])
		elif isinstance(body["message"], dict):
			message = body["message"]
		cid = int(message["offer_id"].get("cid", 0))
		buyer_address = message["offer_id"].get("buyer_address")
		coinid = message.get("coinid")

		if not all([cid, buyer_address, coinid]):
			self.set_status(400)
			self.write({"error":400, "reason": "Missed required fields."})
			raise tornado.web.Finish

		if coinid in settings.bridges.keys():
			self.account.blockchain.setendpoint(settings.bridges[coinid])
		else:
			self.set_status(400)
			self.write({"error":400, "reason":"Invalid coin ID"})
			raise tornado.web.Finish

		check = self.account.validator[coinid](public_key)

		account = await self.account.getaccountdata(public_key=public_key)
		if "error" in account.keys():
			error_code = account["error"]
			self.set_status(error_code)
			self.write(account)
			raise tornado.web.Finish
	
		# Check if one of sellers or buyers rejects offer
		owneraddr = await self.account.blockchain.ownerbycid(cid=cid)
		hex_ = check
		if buyer_address != hex_ and owneraddr != hex_:
			# Avoid rejecting offer
			self.set_status(403)
			self.write({"error": 403, "reason":"Forbidden. Offer does not belong to user."})
		
		# Reject offer
		response = await self.account.blockchain.rejectoffer(coinid=coinid, cid=cid, 
															buyer_address=buyer_address)
		if "error" in response.keys():
			self.set_status(response["error"])
			self.write(response)
			raise tornado.web.Finish

		# Get buyer for email sending
		buyer = await self.account.getaccountbywallet(wallet=buyer_address)
		if "error" in buyer.keys():
			self.set_status(buyer["error"])
			self.write(buyer)
			raise tornado.web.Finish
	
		if buyer.get("email"):
			emaildata = {
				"to": buyer.get("email"),
				"subject": "Robin8 support",
     			"optional": "Your offer with cid %s was rejected." % cid
			}
			await self.account.mailer.sendmail(**emaildata)
		
		# Undeposit balance
		price = await self.account.blockchain.getwriteprice(cid=cid)
		coinid = "PUT"
		await self.account.balance.unfreeze(uid=buyer["id"],coinid=coinid, 
													amount=price)

		del response["result"]
		self.write(response)
767261
function scrypt (key, salt, N, r, p, dkLen, progressCallback) {
  if (N === 0 || (N & (N - 1)) !== 0) throw Error('N must be > 0 and a power of 2')

  if (N > MAX_VALUE / 128 / r) throw Error('Parameter N is too large')
  if (r > MAX_VALUE / 128 / p) throw Error('Parameter r is too large')

  var XY = new Buffer(256 * r)
  var V = new Buffer(128 * r * N)

  // pseudo global
  var B32 = new Int32Array(16) // salsa20_8
  var x = new Int32Array(16) // salsa20_8
  var _X = new Buffer(64) // blockmix_salsa8

  // pseudo global
  var B = crypto.pbkdf2Sync(key, salt, 1, p * 128 * r, 'sha256')

  var tickCallback
  if (progressCallback) {
    var totalOps = p * N * 2
    var currentOp = 0

    tickCallback = function () {
      ++currentOp

      // send progress notifications once every 1,000 ops
      if (currentOp % 1000 === 0) {
        progressCallback({
          current: currentOp,
          total: totalOps,
          percent: (currentOp / totalOps) * 100.0
        })
      }
    }
  }

  for (var i = 0; i < p; i++) {
    smix(B, i * 128 * r, r, N, V, XY)
  }

  return crypto.pbkdf2Sync(key, B, 1, dkLen, 'sha256')

  // all of these functions are actually moved to the top
  // due to function hoisting

  function smix (B, Bi, r, N, V, XY) {
    var Xi = 0
    var Yi = 128 * r
    var i

    B.copy(XY, Xi, Bi, Bi + Yi)

    for (i = 0; i < N; i++) {
      XY.copy(V, i * Yi, Xi, Xi + Yi)
      blockmix_salsa8(XY, Xi, Yi, r)

      if (tickCallback) tickCallback()
    }

    for (i = 0; i < N; i++) {
      var offset = Xi + (2 * r - 1) * 64
      var j = XY.readUInt32LE(offset) & (N - 1)
      blockxor(V, j * Yi, XY, Xi, Yi)
      blockmix_salsa8(XY, Xi, Yi, r)

      if (tickCallback) tickCallback()
    }

    XY.copy(B, Bi, Xi, Xi + Yi)
  }

  function blockmix_salsa8 (BY, Bi, Yi, r) {
    var i

    arraycopy(BY, Bi + (2 * r - 1) * 64, _X, 0, 64)

    for (i = 0; i < 2 * r; i++) {
      blockxor(BY, i * 64, _X, 0, 64)
      salsa20_8(_X)
      arraycopy(_X, 0, BY, Yi + (i * 64), 64)
    }

    for (i = 0; i < r; i++) {
      arraycopy(BY, Yi + (i * 2) * 64, BY, Bi + (i * 64), 64)
    }

    for (i = 0; i < r; i++) {
      arraycopy(BY, Yi + (i * 2 + 1) * 64, BY, Bi + (i + r) * 64, 64)
    }
  }

  function R (a, b) {
    return (a << b) | (a >>> (32 - b))
  }

  function salsa20_8 (B) {
    var i

    for (i = 0; i < 16; i++) {
      B32[i] = (B[i * 4 + 0] & 0xff) << 0
      B32[i] |= (B[i * 4 + 1] & 0xff) << 8
      B32[i] |= (B[i * 4 + 2] & 0xff) << 16
      B32[i] |= (B[i * 4 + 3] & 0xff) << 24
      // B32[i] = B.readUInt32LE(i*4)   <--- this is signficantly slower even in Node.js
    }

    arraycopy(B32, 0, x, 0, 16)

    for (i = 8; i > 0; i -= 2) {
      x[4] ^= R(x[0] + x[12], 7)
      x[8] ^= R(x[4] + x[0], 9)
      x[12] ^= R(x[8] + x[4], 13)
      x[0] ^= R(x[12] + x[8], 18)
      x[9] ^= R(x[5] + x[1], 7)
      x[13] ^= R(x[9] + x[5], 9)
      x[1] ^= R(x[13] + x[9], 13)
      x[5] ^= R(x[1] + x[13], 18)
      x[14] ^= R(x[10] + x[6], 7)
      x[2] ^= R(x[14] + x[10], 9)
      x[6] ^= R(x[2] + x[14], 13)
      x[10] ^= R(x[6] + x[2], 18)
      x[3] ^= R(x[15] + x[11], 7)
      x[7] ^= R(x[3] + x[15], 9)
      x[11] ^= R(x[7] + x[3], 13)
      x[15] ^= R(x[11] + x[7], 18)
      x[1] ^= R(x[0] + x[3], 7)
      x[2] ^= R(x[1] + x[0], 9)
      x[3] ^= R(x[2] + x[1], 13)
      x[0] ^= R(x[3] + x[2], 18)
      x[6] ^= R(x[5] + x[4], 7)
      x[7] ^= R(x[6] + x[5], 9)
      x[4] ^= R(x[7] + x[6], 13)
      x[5] ^= R(x[4] + x[7], 18)
      x[11] ^= R(x[10] + x[9], 7)
      x[8] ^= R(x[11] + x[10], 9)
      x[9] ^= R(x[8] + x[11], 13)
      x[10] ^= R(x[9] + x[8], 18)
      x[12] ^= R(x[15] + x[14], 7)
      x[13] ^= R(x[12] + x[15], 9)
      x[14] ^= R(x[13] + x[12], 13)
      x[15] ^= R(x[14] + x[13], 18)
    }

    for (i = 0; i < 16; ++i) B32[i] = x[i] + B32[i]

    for (i = 0; i < 16; i++) {
      var bi = i * 4
      B[bi + 0] = (B32[i] >> 0 & 0xff)
      B[bi + 1] = (B32[i] >> 8 & 0xff)
      B[bi + 2] = (B32[i] >> 16 & 0xff)
      B[bi + 3] = (B32[i] >> 24 & 0xff)
      // B.writeInt32LE(B32[i], i*4)  //<--- this is signficantly slower even in Node.js
    }
  }

  // naive approach... going back to loop unrolling may yield additional performance
  function blockxor (S, Si, D, Di, len) {
    for (var i = 0; i < len; i++) {
      D[Di + i] ^= S[Si + i]
    }
  }
}
659273
function TransactionBuilder (network, maximumFeeRate) {
  this.prevTxMap = {}
  this.network = network || networks.bitcoin

  // WARNING: This is __NOT__ to be relied on, its just another potential safety mechanism (safety in-depth)
  this.maximumFeeRate = maximumFeeRate || 2500

  this.inputs = []
  this.tx = new Transaction(this.network)
}
542090
def create(ctx, to, amount, symbol, secret, hash, account, expiration):
    
    ctx.blockchain.blocking = True
    tx = ctx.blockchain.htlc_create(
        Amount(amount, symbol),
        to,
        secret,
        hash_type=hash,
        expiration=expiration,
        account=account,
    )
    tx.pop("trx", None)
    print_tx(tx)
    results = tx.get("operation_results", {})
    if results:
        htlc_id = results[0][1]
        print("Your htlc_id is: {}".format(htlc_id))
728861
def broadcast_transaction(hex_tx, blockchain_client):
    
    if not isinstance(blockchain_client, ChainComClient):
        raise Exception('A ChainComClient object is required')

    auth = blockchain_client.auth
    if not auth or len(auth) != 2:
        raise Exception('ChainComClient object must have auth credentials.')

    url = CHAIN_API_BASE_URL + '/bitcoin/transactions/send'
    payload = json.dumps({ 'signed_hex': hex_tx })
    r = requests.post(url, data=payload, auth=auth)

    try:
        data = r.json()
    except ValueError, e:
        raise Exception('Received non-JSON from chain.com.')

    if 'transaction_hash' in data:
        reply = {}
        reply['tx_hash'] = data['transaction_hash']
        reply['success'] = True
        return reply
    else:
        raise Exception('Tx hash missing from chain.com response: ' + str(data) + '\noriginal: ' + str(payload))
1368899
function Transaction (network = networks.bitcoin) {
  this.version = 1
  this.locktime = 0
  this.ins = []
  this.outs = []
  this.network = network
  if (coins.isZcash(network)) {
    // ZCash version >= 2
    this.joinsplits = []
    this.joinsplitPubkey = []
    this.joinsplitSig = []
    // ZCash version >= 3
    this.overwintered = 0  // 1 if the transaction is post overwinter upgrade, 0 otherwise
    this.versionGroupId = 0  // 0x03C48270 (63210096) for overwinter and 0x892F2085 (2301567109) for sapling
    this.expiryHeight = 0  // Block height after which this transactions will expire, or 0 to disable expiry
    // ZCash version >= 4
    this.valueBalance = 0
    this.vShieldedSpend = []
    this.vShieldedOutput = []
    this.bindingSig = 0
  }
  if (coins.isDash(network)) {
    // Dash version = 3
    this.type = 0
    this.extraPayload = Buffer.alloc(0)
  }
}
1096203
function (params) {
  const oThis = this
  ;

  params = params || {};
  oThis.transactionHash = params.transaction_hash;
  oThis.chain = 'value';
}
571265
function createOutTransfer (dappId, transactionId, recipientId, amount, secret, secondSecret, timeOffset) {
	var now = new Date().getTime();
	var time = timeOffset ? now - timeOffset : now;
	var keys = crypto.getKeys(secret);

	var transaction = {
		type: 7,
		amount: amount,
		fee: constants.fees.send,
		recipientId: recipientId,
		senderPublicKey: keys.publicKey,
		timestamp: slots.getTime(time),
		asset: {
			outTransfer: {
				dappId: dappId,
				transactionId: transactionId,
			},
		},
	};

	crypto.sign(transaction, keys);

	if (secondSecret) {
		var secondKeys = crypto.getKeys(secondSecret);
		crypto.secondSign(transaction, secondKeys);
	}

	return transaction;
}
169694
def get_transaction(self, account_id, transaction_id, **params):
        """"""
        response = self._get(
            'v2', 'accounts', account_id, 'transactions', transaction_id, params=params)
        return self._make_api_object(response, Transaction)
492977
async function () {
    const oThis = this
      , web3Provider = web3ProviderFactory.getProvider(oThis.chain, 'ws')
      , abi = coreAddresses.getAbiForContract(oThis.contractName)
      , contractObj = new web3Provider.eth.Contract(abi)
      , bufferGasLimit = 10000
    ;

    contractObj.options.address = oThis.contractAddress;
    //contractObj.setProvider(web3Provider.currentProvider);

    const transactionOptions = {
      from: oThis.senderAddress,
      gasPrice: (oThis.chain === 'value') ? VC_GAS_PRICE : UC_GAS_PRICE,
      gas: (oThis.chain === 'value') ? VC_GAS_LIMIT : UC_GAS_LIMIT
    };

    const scope = contractObj.methods
      , gasToUse = await (scope[oThis.methodName].apply(scope,
      (oThis.methodArguments || []))).estimateGas(transactionOptions);

    return responseHelper.successWithData({gas_to_use: gasToUse + bufferGasLimit});
  }
1218558
def create(self,rate, amount, order_type, pair):
        '''  
        '''
        nonce = nounce()
        payload = { 'rate': rate,
                    'amount': amount,
                    'order_type': order_type,
                    'pair': pair
                    }
        url= 'https://coincheck.com/api/exchange/orders'
        body = 'rate={rate}&amount={amount}&order_type={order_type}&pair={pair}'.format(**payload)
        message = nonce + url + body
        signature = hmac.new(self.secret_key.encode('utf-8'), message.encode('utf-8'), hashlib.sha256).hexdigest()
        headers = {
           'ACCESS-KEY'      : self.access_key,
           'ACCESS-NONCE'    : nonce,
           'ACCESS-SIGNATURE': signature
        }
        r = requests.post(url,headers=headers,data=body)
        return json.loads(r.text)
58012
def make_send_to_address_tx(recipient_address, amount, private_key,
        blockchain_client=BlockchainInfoClient(), fee=STANDARD_FEE,
        change_address=None):
    
    # get out the private key object, sending address, and inputs
    private_key_obj, from_address, inputs = analyze_private_key(private_key,
        blockchain_client)
    # get the change address
    if not change_address:
        change_address = from_address
    # create the outputs
    outputs = make_pay_to_address_outputs(recipient_address, amount, inputs,
                                          change_address, fee=fee)
    # serialize the transaction
    unsigned_tx = serialize_transaction(inputs, outputs)

    # generate a scriptSig for each input
    for i in xrange(0, len(inputs)):
        signed_tx = sign_transaction(unsigned_tx, i, private_key_obj.to_hex())
        unsigned_tx = signed_tx

    # return the signed tx
    return signed_tx
982961
def base_fee(self):
        
        latest_ledger = self.ledgers(order='desc', limit=1)
        try:
            base_fee = latest_ledger['_embedded']['records'][0]['base_fee_in_stroops']
        except (KeyError, IndexError):
            base_fee = 100
        return base_fee
406182
def poll(
            self,
            transaction_hash: bytes,
    ):
        
        if len(transaction_hash) != 32:
            raise ValueError(
                'transaction_hash must be a 32 byte hash',
            )

        transaction_hash = encode_hex(transaction_hash)

        # used to check if the transaction was removed, this could happen
        # if gas price is too low:
        #
        # > Transaction (acbca3d6) below gas price (tx=1 Wei ask=18
        # > Shannon). All sequential txs from this address(7d0eae79)
        # > will be ignored
        #
        last_result = None

        while True:
            # Could return None for a short period of time, until the
            # transaction is added to the pool
            transaction = self.web3.eth.getTransaction(transaction_hash)

            # if the transaction was added to the pool and then removed
            if transaction is None and last_result is not None:
                raise Exception('invalid transaction, check gas price')

            # the transaction was added to the pool and mined
            if transaction and transaction['blockNumber'] is not None:
                last_result = transaction

                # this will wait for both APPLIED and REVERTED transactions
                transaction_block = transaction['blockNumber']
                confirmation_block = transaction_block + self.default_block_num_confirmations

                block_number = self.block_number()

                if block_number >= confirmation_block:
                    return transaction

            gevent.sleep(1.0)