def build_unsigned_single_tx(amount, fees, outputs):
        '''
        Builds an unsigned tx and returns it in a list
        '''
        txs = build_valid_single_tx(amount, fees, outputs)
        txjson = deserialize(txs[0])
        for inp in txjson["ins"]: inp['script'] = ''
        return [serialize(txjson)]
Beispiel #2
0
def trade(sender_addr, value, target_addr, fee=0.0001, change_addr=None):

    unspent_outputs = unspent(sender_addr)
    satoshis_value = covert_satoshis(value)
    satoshis_fee = covert_satoshis(fee)

    inputs, change = select_outputs(unspent_outputs, satoshis_value,
                                    satoshis_fee)
    if inputs:
        if not change_addr:
            change_addr = sender_addr
        outputs = build_tx_params(target_addr, satoshis_value, change_addr,
                                  change)
        tx = mktx(inputs, outputs)
        print "构建的建议信息是:"
        print "由%s --->>> %s转账%sBTC, 手续费为%sBTC, 找零地址:%s" % (
            sender_addr, target_addr, value, fee, change_addr)
        print "-----" * 30
        print tx
        print "#####" * 30
        print deserialize(tx)
        print "*****" * 30
    else:
        print "余额不足"
Beispiel #3
0
def is_testnet(inp):
    '''Checks if inp is a testnet address, TXID or Push TxHex''' 
    if len(inp) > 0 and isinstance(inp, (list, tuple)):
        res = []
        for v in inp:
            if not v or (isinstance(v, basestring) and v.lower() in ("btc", "testnet")): 
                pass
            try: 
                res.append(is_testnet(v))
            except: 
                return False
        return any(res)
    elif not isinstance(inp, basestring):    # sanity check
        raise TypeError("Cannot check %s, only string or dict" % str(type(inp)))

    ## ADDRESSES
    if inp[0] in "123mn":
        if re.match("^[2mn][a-km-zA-HJ-NP-Z0-9]{26,33}$", inp):
            return True 
        elif re.match("^[13][a-km-zA-HJ-NP-Z0-9]{26,33}$", inp):
            return False
        sys.stderr.write("Bad address format %s")
    ## TXID
    elif re.match('^[0-9a-fA-F]{64}$', inp):
        try:
            jdata = json.loads(make_request("%s/tx/%s" % (BET_URL, inp)))    # Try Testnet
            return True 
        except:
            jdata = json.loads(make_request("%s/tx/%s" % (BE_URL, inp)))     # Try Mainnet
            return False
        sys.stderr.write("TxID %s has no match for testnet or mainnet (Bad TxID)")

    ## PUSHTX
    elif (inp[:8] == '01000000' or inp[:4] == b'\x01\x00\x00\x00'):
        from bitcoin.transaction import serialize, deserialize
        txo = deserialize(inp)
        if len(txo.get("ins")) > 0:
            pass
        return False
    else:
        raise TypeError("{0} is unknown input".format(inp))
  def check_amount_fees_redeemable(self, seller_amount, network = MAINNET, fctn = blockr_sum_inputs):
      '''
      Extracts amount and fees proposed by the buyer
      from a list of transactions and from the previous amount proposed by the seller
      It also checks if all transactions are redeemable
              
      Parameters:
          seller_amount = amount proposed by the seller
          network       = network used
          fctn          = function used to compute the sum of the inputs for a given transaction
                          by querying the blockchain
                          see bc.api.blockr_sum_inputs() for signature and returned value
      '''
      is_redeemable = True
      sum_inp = 0
      sum_out = 0
      # Checks inputs unicity over all txs
      if not check_inputs_unicity(self.transactions):
          is_redeemable = False
          raise UtxoError('Duplicated TXOs')        
      for tx in self.transactions:
          # Deserializes the transaction
          txjson = tx if (type(tx) == dict) else deserialize(tx)
          sum_inp_tx =  fctn(tx, network)
          sum_out_tx = sum([o['value'] for o in txjson['outs']])
          sum_inp += sum_inp_tx
          sum_out += sum_out_tx
          if sum_inp_tx < sum_out_tx: is_redeemable = False
      # Computes amount and fees proposed by the buyer
      sum_fee = max(0, sum_inp - sum_out)
      buyer_amount = sum_inp - (sum_fee + sum_out - seller_amount)
      # Stores results
      self.amount = buyer_amount
      self.fees = sum_fee
      self.is_redeemable = is_redeemable
 
  
      
        "transaction is not a valid Bitcoin transaction."
    sys.exit()

# Check to make sure the input string is actually a hex string.
if all(txChars in string.hexdigits for txChars in sys.argv[1]) == False:
    print "The hex Tx string has non-hex characters. Please check the string."
    sys.exit()

# Ideally, there would be a function that would make sure the incoming hex
# string would be validated to make sure that it's an actual Bitcoin
# transaction. Unfortunately, pybitcointools doesn't appear to have this
# functionality. So, we have to fly blind. We'll account for this as best we can
# by catching any errors and just assuming it's a bad input string. This isn't
# ideal. It works for now, though.
#
# Call the function that generates the JSON output, and then output the JSON
# string as one line and as a more readable, tab-delimited piece of text.
try:
    txResult = deserialize(sys.argv[1])
    print '\nRaw JSON string:'
    print json.dumps(txResult)
    print '\nIndented JSON string:'
    print json.dumps(txResult, indent=4, sort_keys=True, cls=UniversalEncoder)
    print '\nJSON-encoded string:'
    print '{\"jsonData\":\"%s\"}' % json.dumps(txResult)
    print '\nJSON-encoded string (backslash-escaped):'
    print '{\"jsonData\":\"%s\"}' % json.dumps(txResult).replace('"', r'\"')
except:
    print 'The hex input string isn\'t a valid Bitcoin Tx. Please double ' \
        'check the input string.'
 def format_txs(txs):
     if txs is None: return ''
     return str([json.dumps(deserialize(tx)) for tx in txs])