Example #1
0
 def getMerkleRoot(self):
    assert( not self.numTx == UNINITIALIZED )
    if len(self.merkleTree)==0 and not self.numTx==0:
       #Create the merkle tree
       self.merkleTree = [hash256(tx.serializeWithoutWitness()) for tx in self.txList]
       sz = len(self.merkleTree)
       while sz > 1:
          hashes = self.merkleTree[-sz:]
          mod2 = sz%2
          for i in range(sz/2):
             self.merkleTree.append( hash256(hashes[2*i] + hashes[2*i+1]) )
          if mod2==1:
             self.merkleTree.append( hash256(hashes[-1] + hashes[-1]) )
          sz = (sz+1) / 2
    self.merkleRoot = self.merkleTree[-1]
    return self.merkleRoot
Example #2
0
def getTx(tx, blkNum):
   binunpacker = BinaryUnpacker(tx)
   txData = Tx(hash256(tx), binunpacker.get(UINT32),[], [])
   txInCount = binunpacker.get(VAR_INT)
   for i in range(txInCount):
      outPoint = OutPoint(binunpacker.get(BINARY_CHUNK, TX_OUT_HASH_LENGTH),binunpacker.get(UINT32), blkNum)
      txInLength = binunpacker.get(VAR_INT)
      script = binunpacker.get(BINARY_CHUNK, txInLength)
      sequence = binunpacker.get(UINT32)
      txData.txInList.append(TxIn(outPoint, script, sequence))
   txOutCount = binunpacker.get(VAR_INT)   
   for j in range(txOutCount):
      value = binunpacker.get(UINT64)
      scriptLength = binunpacker.get(VAR_INT)
      if scriptLength > 0:
         script = binunpacker.get(BINARY_CHUNK,scriptLength)
         opcode = binary_to_int(script[:1])
         if opcode < 75 and len(script)==2+opcode and binary_to_int(script[1+opcode:], BIGENDIAN) == OP_CHECKSIG:
            txOutType = PAY_TO_PUBLIC_KEY
         elif opcode == OP_DUP and binary_to_int(script[-2]) == OP_EQUALVERIFY and binary_to_int(script[-1]) == OP_CHECKSIG:
            txOutType = PAY_TO_PUBKEY_HASH 
         elif opcode == OP_HASH160 and binary_to_int(script[1]) == 20 and binary_to_int(script[-1]) == OP_EQUAL:
            txOutType = PAY_TO_SCRIPT_HASH
         elif opcode == P2POOL_LAST_TX_OUT_OP_CODE and len(script) == 1 + opcode:
            txOutType = PAY_TO_POOL_LAST_TX_OUT
         elif opcode in [OP_1,OP_2,OP_3] and binary_to_int(script[-1]) == OP_CHECKMULTISIG:
            txOutType = MULTISIGNATURE
         else:
            txOutType = UNKNOWN  
      else:
         script = None
         txOutType = None
         j = txOutCount
      txData.txOutList.append(TxOut(j, value, script, txOutType))
   return txData
Example #3
0
 def getMerkleRoot(self):
     assert (not self.numTx == UNINITIALIZED)
     if len(self.merkleTree) == 0 and not self.numTx == 0:
         #Create the merkle tree
         self.merkleTree = [hash256(tx.serialize()) for tx in self.txList]
         sz = len(self.merkleTree)
         while sz > 1:
             hashes = self.merkleTree[-sz:]
             mod2 = sz % 2
             for i in range(sz / 2):
                 self.merkleTree.append(
                     hash256(hashes[2 * i] + hashes[2 * i + 1]))
             if mod2 == 1:
                 self.merkleTree.append(hash256(hashes[-1] + hashes[-1]))
             sz = (sz + 1) / 2
     self.merkleRoot = self.merkleTree[-1]
     return self.merkleRoot
Example #4
0
 def serialize(self):
    bp = BinaryPacker()
    bp.put(BINARY_CHUNK, self.magic,                    width= 4)
    bp.put(BINARY_CHUNK, self.cmd.ljust(12, '\x00'),    width=12)
    payloadBin = self.payload.serialize()
    bp.put(UINT32, len(payloadBin))
    bp.put(BINARY_CHUNK, hash256(payloadBin)[:4],     width= 4)
    bp.put(BINARY_CHUNK, payloadBin)
    return bp.getBinaryString()
Example #5
0
 def serialize(self):
     bp = BinaryPacker()
     bp.put(BINARY_CHUNK, self.magic, width=4)
     bp.put(BINARY_CHUNK, self.cmd.ljust(12, '\x00'), width=12)
     payloadBin = self.payload.serialize()
     bp.put(UINT32, len(payloadBin))
     bp.put(BINARY_CHUNK, hash256(payloadBin)[:4], width=4)
     bp.put(BINARY_CHUNK, payloadBin)
     return bp.getBinaryString()
Example #6
0
 def getHash(self, endian=LITTLEENDIAN):
     if self.version == UNINITIALIZED:
         raise UnitializedBlockDataError, 'PyBlockHeader object not initialized!'
     if len(self.theHash) < 32:
         self.theHash = hash256(self.serialize())
     outHash = self.theHash
     if endian == BIGENDIAN:
         outHash = binary_switchEndian(outHash)
     return outHash
Example #7
0
 def getHash(self, endian=LITTLEENDIAN):
    if self.version == UNINITIALIZED:
       raise UnitializedBlockDataError, 'PyBlockHeader object not initialized!'
    if len(self.theHash) < 32:
       self.theHash = hash256(self.serialize())
    outHash = self.theHash
    if endian==BIGENDIAN:
       outHash = binary_switchEndian(outHash)
    return outHash
Example #8
0
def DecodeBase58Check(psz):
   vchRet = b58decode(psz, None)
   key = vchRet[0:-4]
   csum = vchRet[-4:]
   hashValue = hash256(key)
   cs32 = hashValue[0:4]
   if cs32 != csum:
      return None
   else:
      return key
Example #9
0
def DecodeBase58Check(psz):
    vchRet = b58decode(psz, None)
    key = vchRet[0:-4]
    csum = vchRet[-4:]
    hashValue = hash256(key)
    cs32 = hashValue[0:4]
    if cs32 != csum:
        return None
    else:
        return key
Example #10
0
   def unserialize(self, toUnpack):
      if isinstance(toUnpack, BinaryUnpacker):
         blkData = toUnpack
      else:
         blkData = BinaryUnpacker( toUnpack )

      self.version     = blkData.get(UINT32)
      self.prevBlkHash = blkData.get(BINARY_CHUNK, 32)
      self.merkleRoot  = blkData.get(BINARY_CHUNK, 32)
      self.timestamp   = blkData.get(UINT32)
      self.diffBits    = blkData.get(BINARY_CHUNK, 4)
      self.nonce       = blkData.get(UINT32)
      self.theHash     = hash256(self.serialize())
      return self
Example #11
0
    def unserialize(self, toUnpack):
        if isinstance(toUnpack, BinaryUnpacker):
            blkData = toUnpack
        else:
            blkData = BinaryUnpacker(toUnpack)

        self.version = blkData.get(UINT32)
        self.prevBlkHash = blkData.get(BINARY_CHUNK, 32)
        self.merkleRoot = blkData.get(BINARY_CHUNK, 32)
        self.timestamp = blkData.get(UINT32)
        self.diffBits = blkData.get(BINARY_CHUNK, 4)
        self.nonce = blkData.get(UINT32)
        self.theHash = hash256(self.serialize())
        return self
   def testSimpleAddress(self):
      # Execute the tests with Satoshi's public key from the Bitcoin specification page
      satoshiPubKeyHex = '04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284'
      addrPiece1Hex = '65a4358f4691660849d9f235eb05f11fabbd69fa'
      addrPiece1Bin = hex_to_binary(addrPiece1Hex)
      satoshiAddrStr = hash160_to_addrStr(addrPiece1Bin)

      saddr = PyBtcAddress().createFromPublicKey( hex_to_binary(satoshiPubKeyHex) )
      print '\tAddr calc from pubkey: ', saddr.calculateAddrStr()
      self.assertTrue(checkAddrStrValid(satoshiAddrStr))
   
      testAddr = PyBtcAddress().createFromPlainKeyData(PRIVATE_KEY, ADDRESS_20, publicKey65=PUBLIC_KEY)
      msg = int_to_binary(39029348428)
      theHash = hash256(msg)
      derSig = testAddr.generateDERSignature(theHash)
      # Testing ECDSA signing & verification -- arbitrary binary strings:
      self.assertTrue(testAddr.verifyDERSignature( theHash, derSig))
    def testSimpleAddress(self):
        # Execute the tests with Satoshi's public key from the Bitcoin specification page
        satoshiPubKeyHex = '04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284'
        addrPiece1Hex = '65a4358f4691660849d9f235eb05f11fabbd69fa'
        addrPiece1Bin = hex_to_binary(addrPiece1Hex)
        satoshiAddrStr = hash160_to_addrStr(addrPiece1Bin)

        saddr = PyBtcAddress().createFromPublicKey(
            hex_to_binary(satoshiPubKeyHex))
        print '\tAddr calc from pubkey: ', saddr.calculateAddrStr()
        self.assertTrue(checkAddrStrValid(satoshiAddrStr))

        testAddr = PyBtcAddress().createFromPlainKeyData(
            PRIVATE_KEY, ADDRESS_20, publicKey65=PUBLIC_KEY)
        msg = int_to_binary(39029348428)
        theHash = hash256(msg)
        derSig = testAddr.generateDERSignature(theHash)
        # Testing ECDSA signing & verification -- arbitrary binary strings:
        self.assertTrue(testAddr.verifyDERSignature(theHash, derSig))
Example #14
0
 def getHashHex(self, endian=LITTLEENDIAN):
    if self.version == UNINITIALIZED:
       raise UnitializedBlockDataError, 'PyBlockHeader object not initialized!'
    if len(self.theHash) < 32:
       self.theHash = hash256(self.serialize())
    return binary_to_hex(self.theHash, endian)
Example #15
0
def hash_160_to_bc_address(h160, addrtype=0):
    vh160 = chr(addrtype) + h160
    h = hash256(vh160)  #GRS
    addr = vh160 + h[0:4]
    return b58encode(addr)
Example #16
0
 def getHashHex(self, endian=LITTLEENDIAN):
     if self.version == UNINITIALIZED:
         raise UnitializedBlockDataError, 'PyBlockHeader object not initialized!'
     if len(self.theHash) < 32:
         self.theHash = hash256(self.serialize())
     return binary_to_hex(self.theHash, endian)
Example #17
0
 def hashfile(fn):
     f = open(fn, 'r')
     d = hash256(f.read())
     f.close()
     return binary_to_hex(d[:8])
Example #18
0
   return DIFFICULTY_NUMERATOR / getHighestTarget(bits)

def parseBlockHeader(blkHdrBinary):
   binunpack = BinaryUnpacker(blkHdrBinary)
   return BlockHeader(binunpack.get(UINT32),
                      binunpack.get(BINARY_CHUNK, 32),
                      binunpack.get(BINARY_CHUNK, 32),
                      binunpack.get(UINT32),
                      binunpack.get(UINT32),
                      binunpack.get(UINT32))

blkCounter = -1

MERKLE_ROOT_TEST_RESULT = "d6f226837f442e34974d01825cbac711f4c358d1f564747d3d7203a2d4e94619"

dHashList = lambda lst: [hash256(data) for data in lst]

evenList = lambda lst: lst if len(lst) % 2 == 0 else lst + lst[len(lst) - 1:len(lst)]

foldEvenList = lambda lst: [lst[i] + lst[i+1] for i in range(0, len(lst), 2)]

foldList = lambda lst: foldEvenList(evenList(lst))

def computeMerkleRoot(lst, merkleCounter=0):
   # print binary_to_hex(lst[-1])
   if merkleCounter:
      for item in lst:
         print merkleCounter, binary_to_hex(item)
         merkleCounter += 1
      print
   return computeMerkleRoot(dHashList(foldList(lst)), merkleCounter) if len(lst) > 1 else lst[0]
 def hashfile(fn):
    f = open(fn,'r')
    d = hash256(f.read())
    f.close()
    return binary_to_hex(d[:8])
Example #20
0
def hash_160_to_bc_address(h160, addrtype=0):
   vh160 = chr(addrtype) + h160
   h = hash256(vh160)               #GRS
   addr = vh160 + h[0:4]
   return b58encode(addr)