def test_all(self): # fmt: off tests = [ ( "topmost Istanbul Pluto vagabond treadmill Pacific brackish dictator" " goldfish Medusa afflict bravado chatter revolver Dupont midsummer stopwatch" " whimsical cowbell bottomless", ByteArray([ 0xE5, 0x82, 0x94, 0xF2, 0xE9, 0xA2, 0x27, 0x48, 0x6E, 0x8B, 0x06, 0x1B, 0x31, 0xCC, 0x52, 0x8F, 0xD7, 0xFA, 0x3F, 0x19 ]), ), ( "stairway souvenir flytrap recipe adrift upcoming artist positive" " spearhead Pandora spaniel stupendous tonic concurrent transit Wichita lockup" " visitor flagpole escapade", ByteArray([ 0xD1, 0xD4, 0x64, 0xC0, 0x04, 0xF0, 0x0F, 0xB5, 0xC9, 0xA4, 0xC8, 0xD8, 0xE4, 0x33, 0xE7, 0xFB, 0x7F, 0xF5, 0x62, 0x56 ]), ), ] # fmt: on listToLower = lambda l: [x.lower() for x in l] for i, (words, seed) in enumerate(tests): unWords = mnemonic.encode(seed) self.assertListEqual(listToLower(unWords[:len(unWords) - 1]), listToLower(words.split())) unSeed = mnemonic.decode(words.split()) self.assertEqual(seed, unSeed)
def main(): h = ByteArray( "4c6f72656d20697073756d20646f6c6f722073697420616d65742c20636f6e73656374657475722061646970697363696e6720656c69742e20446f6e65632061742066617563696275732073617069656e2c2076656c20666163696c6973697320617263752e20536564207574206d61737361206e6962682e205574206d6f6c6c69732070756c76696e6172206d617373612e20557420756c6c616d636f7270657220646f6c6f7220656e696d2c20696e206d6f6c657374696520656e696d20636f6e64696d656e74756d2061632e20416c697175616d206572617420766f6c75747061742e204e756c6c6120736f64616c657320617420647569206e656320" ) print(h) print(blake_hash(h.bytes()).hex()) print(crypto.hash160(h.bytes()).hex())
def setVoteOrRevoke(txid): if txid == vote: ticket = tDB["ac"] ticket.tinfo.vote = reversed(ByteArray(vote)) if txid == revocation: ticket = tDB["ad"] ticket.tinfo.revocation = reversed(ByteArray(revocation))
def btcDecode(b, pver): """ btcDecode decodes r using the Decred protocol encoding into the receiver. This is part of the Message interface implementation. See deserialize for decoding transactions stored to disk, such as in a database, as opposed to decoding transactions from the wire. """ # The serialized encoding of the version includes the real transaction # version in the lower 16 bits and the transaction serialization type # in the upper 16 bits. b = ByteArray(b) ver = b.pop(4).unLittle().int() tx = MsgTx.new() tx.version = ver & 0xFFFF tx.serType = ver >> 16 # Serialize the transactions depending on their serialization # types. if tx.serType == wire.TxSerializeNoWitness: b, _ = tx.decodePrefix(b, pver) elif tx.serType == wire.TxSerializeOnlyWitness: b, _ = tx.decodeWitness(b, pver, False) elif tx.serType == wire.TxSerializeFull: b, _ = tx.decodePrefix(b, pver) b, _ = tx.decodeWitness(b, pver, True) else: raise NotImplementedError( "MsgTx.BtcDecode: unsupported transaction type") return tx
def submitProof(self, addr, proof, redemptionAddr): addrStr = addr.string() signingKeyB, doubleHashB = self.db(self.selectKeyByProof_, addrStr, proof.b) signingKey = crypto.privKeyFromBytes(ByteArray(bytes(signingKeyB))) # Prepare the redemption script redeemScript = ByteArray(opcode.OP_SHA256) redeemScript += txscript.addData(bytes(doubleHashB)) redeemScript += opcode.OP_EQUALVERIFY redeemScript += txscript.addData(signingKey.pub.serializeCompressed()) redeemScript += opcode.OP_CHECKSIG # Collect all outputs for the address. We could do this from the cache, # but we'll generate a new call to dcrdata instead to make sure we have # the freshest data. utxos = self.blockchain.UTXOs([addrStr]) if len(utxos) == 0: return dict( error="challenge is either unfunded or has already been redeemed", code=1, ) rewardTx = msgtx.MsgTx.new() reward = 0 for utxo in utxos: reward += utxo.satoshis prevOut = msgtx.OutPoint(utxo.txHash, utxo.vout, msgtx.TxTreeRegular) rewardTx.addTxIn(msgtx.TxIn(prevOut, valueIn=utxo.satoshis)) # sigScript = txscript.addData(answerHash) + txscript.addData(script) # rewardTx.addTxIn(msgtx.TxIn(prevOut, signatureScript=sigScript)) # Add the reward output with zero value for now. txout = msgtx.TxOut(pkScript=txscript.payToAddrScript(redemptionAddr)) rewardTx.addTxOut(txout) # Get the serialized size of the transaction. Since there are no signatures # involved, the size is known exactly. Use the size to calculate transaction # fees. # 1 + 73 = signature # 1 + 32 = answer hash # 1 + 70 = redeem script sigScriptSize = 1 + 73 + 1 + 32 + 1 + 70 maxSize = rewardTx.serializeSize() + len(utxos)*sigScriptSize fees = feeRate * maxSize if reward <= fees: return makeErr(f"reward, {reward}, must cover fees {fees}, tx size = {maxSize} bytes, fee rate = {feeRate} atoms/byte") netReward = reward - fees # Set the value on the reward output. txout.value = netReward for idx, txIn in enumerate(rewardTx.txIn): sig = txscript.rawTxInSignature(rewardTx, idx, redeemScript, txscript.SigHashAll, signingKey.key) sigScript = txscript.addData(sig) + txscript.addData(DummyHash) + txscript.addData(redeemScript) txIn.signatureScript = sigScript return { "txHex": rewardTx.serialize().hex(), }
def main(): privKey = ByteArray( "577811a230cf0c352a01bfa044287e9f8b630dacd796e375515377126b8fe046") #msg = ByteArray("a5e4d4d0c3b77a98c5227d6c3255a29428a106aac5e5e2c3a6d7782396e667c4") msg = ByteArray( "62bde5b4c2b855fc32de5586e9c849457453d2ec2aa2f1a539258766d9008295") sig = txscript.signCompact(privKey, msg, True) print(sig.hex())
def test_decodeAddressPubKey(): decoded = ( ByteArray([crypto.STEd25519]) + ByteArray(b"", length=32), ByteArray([crypto.STSchnorrSecp256k1]) + ByteArray(b"", length=32), ) for d in decoded: with pytest.raises(NotImplementedError): addrlib.decodeAddressPubKey(d, testnet)
def test_read_var_int(self, prepareLogger): assert wire.readVarInt(ByteArray([0xFC]), wire.ProtocolVersion) == 0xFC with pytest.raises(DecredError): wire.readVarInt( ByteArray([0xFE, 0xFF, 0xFF, 0x0, 0x0]), wire.ProtocolVersion ) with pytest.raises(DecredError): wire.readVarInt(ByteArray([0xFD, 0xFC, 0x0]), wire.ProtocolVersion)
def test_decodeWitness_errors(self, prepareLogger): tx = msgtx.MsgTx.new() # Too many input transactions. with pytest.raises(DecredError): tx.decodeWitness(ByteArray([0xFE, 0xFF, 0xFF, 0xFF]), 1, False) # Number of signature scripts different from number of TxIns. with pytest.raises(DecredError): tx.decodeWitness(ByteArray([0x01]), 1, True)
def serializeCompressed(self): fmt = PUBKEY_COMPRESSED if not isEven(self.y): fmt |= 0x1 b = ByteArray(fmt) b += ByteArray(self.x, length=COORDINATE_LEN) if len(b) != PUBKEY_COMPRESSED_LEN: raise DecredError("invalid compressed pubkey length %d", len(b)) return b
def bigAffineToField(self, x, y): """ bigAffineToField takes an affine point (x, y) as big integers and converts it to an affine point as field values. """ x3, y3 = FieldVal(), FieldVal() x3.setBytes(ByteArray(x).bytes()) y3.setBytes(ByteArray(y).bytes()) return x3, y3
def writeTxOut(pver, ver, to): """ writeTxOut encodes to into the Decred protocol encoding for a transaction output (TxOut) to w. """ b = ByteArray(to.value, length=8).littleEndian() b += ByteArray(to.version, length=2).littleEndian() b += wire.writeVarBytes(pver, to.pkScript) return b
def writeOutPoint(pver, ver, op): """ writeOutPoint encodes op to the Decred protocol encoding for an OutPoint to w. """ b = op.hash.copy() b += ByteArray(op.index, length=4).littleEndian() b += ByteArray(op.tree, length=1) return b
def main(): script = ByteArray( "512103af3c24d005ca8b755e7167617f3a5b4c60a65f8318a7fcd1b0cacb1abd2a97fc21027b81bc16954e28adb832248140eb58bedb6078ae5f4dabf21fde5a8ab7135cb652ae" ) print(crypto.hash160(script.bytes()).hex()) _, addrs, _ = txscript.extractPkScriptAddrs(0, script, nets.testnet) for addr in addrs: print("addr", addr.string())
def serializeUncompressed(self): """ serializeUncompressed serializes a public key in a 65-byte uncompressed format. """ b = ByteArray(PUBKEY_UNCOMPRESSED) b += ByteArray(self.x, length=32) b += ByteArray(self.y, length=32) return b
def randFieldElement(): """ randFieldElement returns a random element of the field underlying the given curve using the procedure given in [NSA] A.2.1. """ b = ByteArray(generateSeed(curve.BitSize // 8 + 8)) n = curve.N - 1 k = b.int() k = k % n k = k + 1 return k
def test_GetWorkResult(): GET_WORK_RESULT_RAW = dict(data=[0, 1], target=[2, 3]) GET_WORK_RESULT_PARSED = dict(data=ByteArray([0, 1]), target=ByteArray([2, 3])) GET_WORK_RESULT_ATTRS = ("data", "target") do_test( class_=rpc.GetWorkResult, raw=GET_WORK_RESULT_RAW, parsed=GET_WORK_RESULT_PARSED, attrs=GET_WORK_RESULT_ATTRS, )
def unblob(b): """Satisfies the encode.Blobber API""" ver, d = encode.decodeBlob(b) unblobCheck("KDFParams", ver, len(d), {0: 5}) params = KDFParams(salt=ByteArray(d[2]), auth=ByteArray(d[4])) params.kdfFunc = d[0].decode("utf-8") params.hashName = d[1].decode("utf-8") params.iterations = encode.intFromBytes(d[3]) return params
def hash(self): """ Hash returns the BLAKE256 hash of the filter. Returns: ByteArray: The hash. """ # Empty filters have a hash of all zeroes. nData = self.filterNData() if len(nData) == 0: return ByteArray(length=32) return ByteArray(blake_hash(nData.bytes()))
def fromDBRow(row): addr, doubleHash, nonce, prompt, registerTime, imgPath, tweet, flagged, approved = row return Challenge( addr, ByteArray(bytes(doubleHash)), ByteArray(bytes(nonce)), prompt, registerTime, imgPath, tweet, flagged, approved, )
def txWithTxid(txid): txInOne = msgtx.TxIn(msgtx.OutPoint(ByteArray("ff"), 0, 0), valueIn=1) txInTwo = msgtx.TxIn(None, valueIn=3) txOutOne = msgtx.TxOut(pkScript=stakeSubmission, value=3) txOutTwo = msgtx.TxOut() txOutThree = msgtx.TxOut() txOutFour = msgtx.TxOut() txOutFive = msgtx.TxOut() txsIn = [txInOne, txInTwo] txsOut = [txOutOne, txOutTwo, txOutThree, txOutFour, txOutFive] return msgtx.MsgTx(reversed(ByteArray(txid)), None, None, txsIn, txsOut, None, None)
def test_read_var_int(self): self.assertEqual(wire.readVarInt(ByteArray([0xFC]), wire.ProtocolVersion), 0xFC) self.assertRaises( DecredError, wire.readVarInt, ByteArray([0xFE, 0xFF, 0xFF, 0x0, 0x0]), wire.ProtocolVersion, ) self.assertRaises( DecredError, wire.readVarInt, ByteArray([0xFD, 0xFC, 0x0]), wire.ProtocolVersion, )
def match(self, utxo): txid = "ce4913a7fc91a366ae1ba591bb8315755175917369dcf78a9205d597e73dbe3d" assert utxo.address == "Dsa3yVGJK9XFx6L5cC8YzcW3M5Q85wdEXcz" assert utxo.txHash == reversed(ByteArray(txid)) assert utxo.vout == 2 assert utxo.ts == 1581873212 assert utxo.scriptPubKey == ByteArray( "76a91463ae8c6af3c51d3d6e2bb5c5f4be0d623395c5c088ac") assert utxo.height == 424176 assert utxo.satoshis == 942047827 assert utxo.maturity == 0 assert utxo.scriptClass == txscript.PubKeyHashTy assert utxo.txid == txid assert not utxo.isTicket()
def encodeAddress(k, netID): """ Base-58 encode the number, with the netID prepended byte-wise. Args: k (ByteArray): The pubkey or pubkey-hash or script-hash. netID (byte-like): The addresses network encoding ID. Returns: string: Base-58 encoded address. """ b = ByteArray(netID) b += k b += checksum(b.b) return b58encode(b.bytes()).decode()
def btcEncode(self, pver): """ BtcEncode encodes the receiver to w using the Decred protocol encoding. This is part of the Message interface implementation. See Serialize for encoding transactions to be stored to disk, such as in a database, as opposed to encoding transactions for the wire. """ # The serialized encoding of the version includes the real transaction # version in the lower 16 bits and the transaction serialization type # in the upper 16 bits. b = ByteArray(self.version | (self.serType << 16), length=4).littleEndian() if self.serType == wire.TxSerializeNoWitness: b += self.encodePrefix(pver) elif self.serType == wire.TxSerializeOnlyWitness: b += self.encodeWitness(pver) elif self.serType == wire.TxSerializeFull: b += self.encodePrefix(pver) b += self.encodeWitness(pver) else: raise NotImplementedError( "MsgTx.BtcEncode: unsupported transaction type") return b
def test_addr_script_hash(self): pairs = [ ( "52fdfc072182654f163f5f0f9a621d729566c74d", "Dcf2QjJ1pSnLwthhw1cwE55MVZNQVXDZWQT", ), ( "10037c4d7bbb0407d1e2c64981855ad8681d0d86", "DcYvG3fPxHDZ5pzW8nj4rcYq5kM9XFxXpUy", ), ( "d1e91e00167939cb6694d2c422acd208a0072939", "DcrbVYmhm5yX9mw9qdwUVWw6psUhPGrQJsT", ), ( "487f6999eb9d18a44784045d87f3c67cf22746e9", "Dce4vLzzENaZT7D2Wq5crRZ4VwfYMDMWkD9", ), ( "95af5a25367951baa2ff6cd471c483f15fb90bad", "Dcm73og7Hn9PigaNu59dHgKnNSP1myCQ39t", ), ] for scriptHash, addrStr in pairs: addr = addrlib.AddressScriptHash(ByteArray(scriptHash), mainnet) assert addr.string() == addrStr
def test_addr_pubkey_hash(self): pairs = [ ( "e201ee2f37bcc0ba0e93f82322e48333a92b9355", "DsmZvWuokf5NzFwFfJk5cALZZBZivjkhMSQ", ), ( "5643d59202de158b509544d40b32e85bfaf6243e", "DsYq2s8mwpM6vXLbjb8unhNmBXFofPzcrrv", ), ( "c5fa0d15266e055eaf8ec7c4d7a679885266ef0d", "Dsj1iA5PBCU6Nmpe6jqucwfHK17WmSKd3uG", ), ( "73612f7b7b1ed32ff44dded7a2cf87c206fabf8a", "DsbUyd4DueVNyvfh542kZDXNEGKByUAi1RV", ), ( "a616bc09179e31e6d9e3abfcb16ac2d2baf45141", "Dsg76ttvZmTFchZ5mWRnAUg6UGfCyrq86ch", ), ] for pubkeyHash, addrStr in pairs: pubkeyHashBA = ByteArray(pubkeyHash) addr = addrlib.AddressPubKeyHash(pubkeyHashBA, mainnet) assert addr.string() == addrStr assert addr.scriptAddress() == pubkeyHashBA assert addr.hash160() == pubkeyHashBA
def test_encryption(): """ Test encryption and decryption. """ pw = "abc".encode() encryptionKey = crypto.SecretKey(pw) msg = (b"dprv3n8wmhMhC7p7QuzHn4fYgq2d87hQYAxWH3RJ6pYFrd7LAV71RcBQ" b"WrFFmSG3yYWVKrJCbYTBGiniTvKcuuQmi1hA8duKaGM8paYRQNsD1P6") msgEnc = encryptionKey.encrypt(msg) reKey = crypto.SecretKey.rekey(pw, encryptionKey.params()) msgUnenc = reKey.decrypt(msgEnc) assert msg == msgUnenc with pytest.raises(DecredError): crypto.SecretKey.rekey("badpw".encode(), encryptionKey.params()) kp = encryptionKey.params() ogFunc = kp.kdfFunc kp.kdfFunc = "some_other_func" with pytest.raises(DecredError): crypto.SecretKey.rekey(pw, kp) kp.kdfFunc = ogFunc kp.auth = ByteArray(length=32) with pytest.raises(DecredError): crypto.SecretKey.rekey(pw, kp)
def test_addr_secp_pubkey(self): data = [ ( "033b26959b2e1b0d88a050b111eeebcf776a38447f7ae5806b53c9b46e07c267ad", "DkRKjw7LmGCSzBwaUtjQLfb75Zcx9hH8yGNs3qPSwVzZuUKs7iu2e", "e201ee2f37bcc0ba0e93f82322e48333a92b9355", ), ( "0389ced3eaee84d5f0d0e166f6cd15f1bf6f429d1d13709393b418a6fb22d8be53", "DkRLLaJWkmH75iZGtQYE6FEf16zxeHr6TCAF59tGxhds4MFc2HqUS", "5643d59202de158b509544d40b32e85bfaf6243e", ), ( "02a14a0023d7d8cbc5d39fa60f7e4dc4d5bf18a7031f52875fbca6bf837f68713f", "DkM3hdWuKSSTm7Vq8WZx5f294vcZbPkAQYBDswkjmF1CFuWCRYxTr", "c5fa0d15266e055eaf8ec7c4d7a679885266ef0d", ), ( "03c3e3d7cde1c453a6283f5802a73d1cb3827cb4b007f58e3a52a36ce189934b6a", "DkRLn9vzsjK4ZYgDKy7JVYHKGvpZU5CYGK9H8zF2VCWbpTyVsEf4P", "73612f7b7b1ed32ff44dded7a2cf87c206fabf8a", ), ( "0254e17b230e782e591a9910794fdbf9943d500a47f2bf8446e1238f84e809bffc", "DkM37ymaat9j6oTFii1MZVpXrc4aRLEMHhTZrvrz8QY6BZ2HX843L", "a616bc09179e31e6d9e3abfcb16ac2d2baf45141", ), ] for hexKey, addrStr, hash160 in data: addr = addrlib.AddressSecpPubKey(ByteArray(hexKey), mainnet) assert addr.string() == addrStr assert addr.hash160().hex() == hash160
def decodeAddressPubKey(decoded, netParams): """ decodeAddressPubKey decodes a pubkey-type address from the serialized pubkey. Args: decoded (bytes): A 33 bytes decoded pubkey such as would be decoded from a base58 string. The first byte indicates the signature suite. For compressed secp256k1 pubkeys, use AddressSecpPubKey directly. netParams (module): The network parameters. """ if len(decoded) != 33: raise NotImplementedError(f"unable to decode pubkey of length {len(decoded)}") # First byte is the signature suite and ybit. suite = decoded[0] suite &= 127 ybit = not (decoded[0] & (1 << 7) == 0) toAppend = 0x02 if ybit: toAppend = 0x03 if suite == STEcdsaSecp256k1: b = ByteArray(toAppend) + decoded[1:] return AddressSecpPubKey(b, netParams) elif suite == STEd25519: raise NotImplementedError("Edwards signatures not implemented") elif suite == STSchnorrSecp256k1: raise NotImplementedError("Schnorr signatures not implemented") else: raise NotImplementedError(f"unknown address type {suite}")