pax_global_header 0000666 0000000 0000000 00000000064 14302706075 0014516 g ustar 00root root 0000000 0000000 52 comment=7924f4d549e0d93991c663a343e0d835c6d9877a
python-bitcoinlib-python-bitcoinlib-v0.11.2/ 0000775 0000000 0000000 00000000000 14302706075 0021055 5 ustar 00root root 0000000 0000000 python-bitcoinlib-python-bitcoinlib-v0.11.2/.gitignore 0000664 0000000 0000000 00000000133 14302706075 0023042 0 ustar 00root root 0000000 0000000 *.sw?
*.pyc
local*.cfg
.coverage
.tox/
build/
htmlcov/
python_bitcoinlib.egg-info/
dist/
python-bitcoinlib-python-bitcoinlib-v0.11.2/.travis.yml 0000664 0000000 0000000 00000000226 14302706075 0023166 0 ustar 00root root 0000000 0000000 git:
depth: 9999999
language: python
python:
- "3.4"
- "3.5"
- "3.6"
- "3.7"
# command to run tests
script: python3 -m unittest discover -v
python-bitcoinlib-python-bitcoinlib-v0.11.2/LICENSE 0000664 0000000 0000000 00000017737 14302706075 0022101 0 ustar 00root root 0000000 0000000 python-bitcoinlib is free software: you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your option)
any later version.
python-bitcoinlib is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
below for more details.
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
python-bitcoinlib-python-bitcoinlib-v0.11.2/MANIFEST.in 0000664 0000000 0000000 00000000064 14302706075 0022613 0 ustar 00root root 0000000 0000000 include LICENSE README.md
graft bitcoin/tests/data/
python-bitcoinlib-python-bitcoinlib-v0.11.2/README.md 0000664 0000000 0000000 00000007707 14302706075 0022347 0 ustar 00root root 0000000 0000000 # python-bitcoinlib
This Python3 library provides an easy interface to the bitcoin data
structures and protocol. The approach is low-level and "ground up", with a
focus on providing tools to manipulate the internals of how Bitcoin works.
"The Swiss Army Knife of the Bitcoin protocol." - Wladimir J. van der Laan
## Requirements
sudo apt-get install libssl-dev
The RPC interface, `bitcoin.rpc`, is designed to work with Bitcoin Core v0.16.0.
Older versions may work but there do exist some incompatibilities.
## Structure
Everything consensus critical is found in the modules under bitcoin.core. This
rule is followed pretty strictly, for instance chain parameters are split into
consensus critical and non-consensus-critical.
bitcoin.core - Basic core definitions, datastructures, and
(context-independent) validation
bitcoin.core.key - ECC pubkeys
bitcoin.core.script - Scripts and opcodes
bitcoin.core.scripteval - Script evaluation/verification
bitcoin.core.serialize - Serialization
In the future the bitcoin.core may use the Satoshi sourcecode directly as a
library. Non-consensus critical modules include the following:
bitcoin - Chain selection
bitcoin.base58 - Base58 encoding
bitcoin.bloom - Bloom filters (incomplete)
bitcoin.net - Network communication (in flux)
bitcoin.messages - Network messages (in flux)
bitcoin.rpc - Bitcoin Core RPC interface support
bitcoin.wallet - Wallet-related code, currently Bitcoin address and
private key support
Effort has been made to follow the Satoshi source relatively closely, for
instance Python code and classes that duplicate the functionality of
corresponding Satoshi C++ code uses the same naming conventions: CTransaction,
CBlockHeader, nValue etc. Otherwise Python naming conventions are followed.
## Mutable vs. Immutable objects
Like the Bitcoin Core codebase CTransaction is immutable and
CMutableTransaction is mutable; unlike the Bitcoin Core codebase this
distinction also applies to COutPoint, CTxIn, CTxOut, and CBlock.
## Endianness Gotchas
Rather confusingly Bitcoin Core shows transaction and block hashes as
little-endian hex rather than the big-endian the rest of the world uses for
SHA256. python-bitcoinlib provides the convenience functions x() and lx() in
bitcoin.core to convert from big-endian and little-endian hex to raw bytes to
accommodate this. In addition see b2x() and b2lx() for conversion from bytes to
big/little-endian hex.
## Module import style
While not always good style, it's often convenient for quick scripts if
`import *` can be used. To support that all the modules have `__all__` defined
appropriately.
# Example Code
See `examples/` directory. For instance this example creates a transaction
spending a pay-to-script-hash transaction output:
$ PYTHONPATH=. examples/spend-p2sh-txout.py
## Selecting the chain to use
Do the following:
import bitcoin
bitcoin.SelectParams(NAME)
Where NAME is one of 'testnet', 'mainnet', 'signet', or 'regtest'. The chain currently
selected is a global variable that changes behavior everywhere, just like in
the Satoshi codebase.
## Unit tests
Under bitcoin/tests using test data from Bitcoin Core. To run them:
python3 -m unittest discover
Alternately, if Tox (see https://tox.readthedocs.org/) is available on your
system, you can run unit tests for multiple Python versions:
./runtests.sh
HTML coverage reports can then be found in the htmlcov/ subdirectory.
## Documentation
Sphinx documentation is in the "doc" subdirectory. Run "make help" from there
to see how to build. You will need the Python "sphinx" package installed.
Currently this is just API documentation generated from the code and
docstrings. Higher level written docs would be useful, perhaps starting with
much of this README. Pages are written in reStructuredText and linked from
index.rst.
python-bitcoinlib-python-bitcoinlib-v0.11.2/bitcoin/ 0000775 0000000 0000000 00000000000 14302706075 0022504 5 ustar 00root root 0000000 0000000 python-bitcoinlib-python-bitcoinlib-v0.11.2/bitcoin/__init__.py 0000664 0000000 0000000 00000006577 14302706075 0024634 0 ustar 00root root 0000000 0000000 # Copyright (C) 2012-2018 The python-bitcoinlib developers
#
# This file is part of python-bitcoinlib.
#
# It is subject to the license terms in the LICENSE file found in the top-level
# directory of this distribution.
#
# No part of python-bitcoinlib, including this file, may be copied, modified,
# propagated, or distributed except according to the terms contained in the
# LICENSE file.
import bitcoin.core
# Note that setup.py can break if __init__.py imports any external
# dependencies, as these might not be installed when setup.py runs. In this
# case __version__ could be moved to a separate version.py and imported here.
__version__ = '0.11.2'
class MainParams(bitcoin.core.CoreMainParams):
MESSAGE_START = b'\xf9\xbe\xb4\xd9'
DEFAULT_PORT = 8333
RPC_PORT = 8332
DNS_SEEDS = (('bitcoin.sipa.be', 'seed.bitcoin.sipa.be'),
('bluematt.me', 'dnsseed.bluematt.me'),
('dashjr.org', 'dnsseed.bitcoin.dashjr.org'),
('bitcoinstats.com', 'seed.bitcoinstats.com'),
('xf2.org', 'bitseed.xf2.org'),
('bitcoin.jonasschnelli.ch', 'seed.bitcoin.jonasschnelli.ch'))
BASE58_PREFIXES = {'PUBKEY_ADDR':0,
'SCRIPT_ADDR':5,
'SECRET_KEY' :128}
BECH32_HRP = 'bc'
class TestNetParams(bitcoin.core.CoreTestNetParams):
MESSAGE_START = b'\x0b\x11\x09\x07'
DEFAULT_PORT = 18333
RPC_PORT = 18332
DNS_SEEDS = (('testnetbitcoin.jonasschnelli.ch', 'testnet-seed.bitcoin.jonasschnelli.ch'),
('petertodd.org', 'seed.tbtc.petertodd.org'),
('bluematt.me', 'testnet-seed.bluematt.me'),
('bitcoin.schildbach.de', 'testnet-seed.bitcoin.schildbach.de'))
BASE58_PREFIXES = {'PUBKEY_ADDR':111,
'SCRIPT_ADDR':196,
'SECRET_KEY' :239}
BECH32_HRP = 'tb'
class SigNetParams(bitcoin.core.CoreSigNetParams):
MESSAGE_START = b'\x0a\x03\xcf\x40'
DEFAULT_PORT = 38333
RPC_PORT = 38332
DNS_SEEDS = (("signet.bitcoin.sprovoost.nl", "seed.signet.bitcoin.sprovoost.nl"))
BASE58_PREFIXES = {'PUBKEY_ADDR':111,
'SCRIPT_ADDR':196,
'SECRET_KEY' :239}
BECH32_HRP = 'tb'
class RegTestParams(bitcoin.core.CoreRegTestParams):
MESSAGE_START = b'\xfa\xbf\xb5\xda'
DEFAULT_PORT = 18444
RPC_PORT = 18443
DNS_SEEDS = ()
BASE58_PREFIXES = {'PUBKEY_ADDR':111,
'SCRIPT_ADDR':196,
'SECRET_KEY' :239}
BECH32_HRP = 'bcrt'
"""Master global setting for what chain params we're using.
However, don't set this directly, use SelectParams() instead so as to set the
bitcoin.core.params correctly too.
"""
#params = bitcoin.core.coreparams = MainParams()
params = MainParams()
def SelectParams(name):
"""Select the chain parameters to use
name is one of 'mainnet', 'testnet', or 'regtest'
Default chain is 'mainnet'
"""
global params
bitcoin.core._SelectCoreParams(name)
if name == 'mainnet':
params = bitcoin.core.coreparams = MainParams()
elif name == 'testnet':
params = bitcoin.core.coreparams = TestNetParams()
elif name == 'regtest':
params = bitcoin.core.coreparams = RegTestParams()
elif name == 'signet':
params = bitcoin.core.coreparams = SigNetParams()
else:
raise ValueError('Unknown chain %r' % name)
python-bitcoinlib-python-bitcoinlib-v0.11.2/bitcoin/base58.py 0000664 0000000 0000000 00000007347 14302706075 0024160 0 ustar 00root root 0000000 0000000 # Copyright (C) 2011 Sam Rushing
# Copyright (C) 2013-2014 The python-bitcoinlib developers
#
# This file is part of python-bitcoinlib.
#
# It is subject to the license terms in the LICENSE file found in the top-level
# directory of this distribution.
#
# No part of python-bitcoinlib, including this file, may be copied, modified,
# propagated, or distributed except according to the terms contained in the
# LICENSE file.
"""Base58 encoding and decoding"""
import binascii
import bitcoin.core
B58_DIGITS = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
class Base58Error(Exception):
pass
class InvalidBase58Error(Base58Error):
"""Raised on generic invalid base58 data, such as bad characters.
Checksum failures raise Base58ChecksumError specifically.
"""
pass
def encode(b):
"""Encode bytes to a base58-encoded string"""
# Convert big-endian bytes to integer
n = int('0x0' + binascii.hexlify(b).decode('utf8'), 16)
# Divide that integer into bas58
res = []
while n > 0:
n, r = divmod(n, 58)
res.append(B58_DIGITS[r])
res = ''.join(res[::-1])
# Encode leading zeros as base58 zeros
czero = 0
pad = 0
for c in b:
if c == czero:
pad += 1
else:
break
return B58_DIGITS[0] * pad + res
def decode(s):
"""Decode a base58-encoding string, returning bytes"""
if not s:
return b''
# Convert the string to an integer
n = 0
for c in s:
n *= 58
if c not in B58_DIGITS:
raise InvalidBase58Error('Character %r is not a valid base58 character' % c)
digit = B58_DIGITS.index(c)
n += digit
# Convert the integer to bytes
h = '%x' % n
if len(h) % 2:
h = '0' + h
res = binascii.unhexlify(h.encode('utf8'))
# Add padding back.
pad = 0
for c in s[:-1]:
if c == B58_DIGITS[0]: pad += 1
else: break
return b'\x00' * pad + res
class Base58ChecksumError(Base58Error):
"""Raised on Base58 checksum errors"""
pass
class CBase58Data(bytes):
"""Base58-encoded data
Includes a version and checksum.
"""
def __new__(cls, s):
k = decode(s)
verbyte, data, check0 = k[0:1], k[1:-4], k[-4:]
check1 = bitcoin.core.Hash(verbyte + data)[:4]
if check0 != check1:
raise Base58ChecksumError('Checksum mismatch: expected %r, calculated %r' % (check0, check1))
return cls.from_bytes(data, verbyte[0])
def __init__(self, s):
"""Initialize from base58-encoded string
Note: subclasses put your initialization routines here, but ignore the
argument - that's handled by __new__(), and .from_bytes() will call
__init__() with None in place of the string.
"""
@classmethod
def from_bytes(cls, data, nVersion):
"""Instantiate from data and nVersion"""
if not (0 <= nVersion <= 255):
raise ValueError('nVersion must be in range 0 to 255 inclusive; got %d' % nVersion)
self = bytes.__new__(cls, data)
self.nVersion = nVersion
return self
def to_bytes(self):
"""Convert to bytes instance
Note that it's the data represented that is converted; the checkum and
nVersion is not included.
"""
return b'' + self
def __str__(self):
"""Convert to string"""
vs = bytes([self.nVersion]) + self
check = bitcoin.core.Hash(vs)[0:4]
return encode(vs + check)
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, str(self))
__all__ = (
'B58_DIGITS',
'Base58Error',
'InvalidBase58Error',
'encode',
'decode',
'Base58ChecksumError',
'CBase58Data',
)
python-bitcoinlib-python-bitcoinlib-v0.11.2/bitcoin/bech32.py 0000664 0000000 0000000 00000004023 14302706075 0024123 0 ustar 00root root 0000000 0000000 # Copyright (C) 2017 The python-bitcoinlib developers
#
# This file is part of python-bitcoinlib.
#
# It is subject to the license terms in the LICENSE file found in the top-level
# directory of this distribution.
#
# No part of python-bitcoinlib, including this file, may be copied, modified,
# propagated, or distributed except according to the terms contained in the
# LICENSE file.
"""Bech32 encoding and decoding"""
from bitcoin.segwit_addr import encode, decode
import bitcoin
class Bech32Error(Exception):
pass
class Bech32ChecksumError(Bech32Error):
pass
class CBech32Data(bytes):
"""Bech32-encoded data
Includes a witver and checksum.
"""
def __new__(cls, s):
"""from bech32 addr to """
witver, data = decode(bitcoin.params.BECH32_HRP, s)
if witver is None and data is None:
raise Bech32Error('Bech32 decoding error')
return cls.from_bytes(witver, data)
def __init__(self, s):
"""Initialize from bech32-encoded string
Note: subclasses put your initialization routines here, but ignore the
argument - that's handled by __new__(), and .from_bytes() will call
__init__() with None in place of the string.
"""
@classmethod
def from_bytes(cls, witver, witprog):
"""Instantiate from witver and data"""
if not (0 <= witver <= 16):
raise ValueError('witver must be in range 0 to 16 inclusive; got %d' % witver)
self = bytes.__new__(cls, witprog)
self.witver = witver
return self
def to_bytes(self):
"""Convert to bytes instance
Note that it's the data represented that is converted; the checkum and
witver is not included.
"""
return b'' + self
def __str__(self):
"""Convert to string"""
return encode(bitcoin.params.BECH32_HRP, self.witver, self)
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, str(self))
__all__ = (
'Bech32Error',
'Bech32ChecksumError',
'CBech32Data',
)
python-bitcoinlib-python-bitcoinlib-v0.11.2/bitcoin/bloom.py 0000664 0000000 0000000 00000013314 14302706075 0024170 0 ustar 00root root 0000000 0000000 # Copyright (C) 2013-2014 The python-bitcoinlib developers
#
# This file is part of python-bitcoinlib.
#
# It is subject to the license terms in the LICENSE file found in the top-level
# directory of this distribution.
#
# No part of python-bitcoinlib, including this file, may be copied, modified,
# propagated, or distributed except according to the terms contained in the
# LICENSE file.
"""Bloom filter support"""
import struct
import math
import bitcoin.core
import bitcoin.core.serialize
def _ROTL32(x, r):
assert x <= 0xFFFFFFFF
return ((x << r) & 0xFFFFFFFF) | (x >> (32 - r))
def MurmurHash3(nHashSeed, vDataToHash):
"""MurmurHash3 (x86_32)
Used for bloom filters. See http://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp
"""
assert nHashSeed <= 0xFFFFFFFF
h1 = nHashSeed
c1 = 0xcc9e2d51
c2 = 0x1b873593
# body
i = 0
while (i < len(vDataToHash) - len(vDataToHash) % 4
and len(vDataToHash) - i >= 4):
k1 = struct.unpack(b"= 3:
k1 ^= vDataToHash[j+2] << 16
if len(vDataToHash) & 3 >= 2:
k1 ^= vDataToHash[j+1] << 8
if len(vDataToHash) & 3 >= 1:
k1 ^= vDataToHash[j]
k1 &= 0xFFFFFFFF
k1 = (k1 * c1) & 0xFFFFFFFF
k1 = _ROTL32(k1, 15)
k1 = (k1 * c2) & 0xFFFFFFFF
h1 ^= k1
# finalization
h1 ^= len(vDataToHash) & 0xFFFFFFFF
h1 ^= (h1 & 0xFFFFFFFF) >> 16
h1 *= 0x85ebca6b
h1 ^= (h1 & 0xFFFFFFFF) >> 13
h1 *= 0xc2b2ae35
h1 ^= (h1 & 0xFFFFFFFF) >> 16
return h1 & 0xFFFFFFFF
class CBloomFilter(bitcoin.core.serialize.Serializable):
# 20,000 items with fp rate < 0.1% or 10,000 items and <0.0001%
MAX_BLOOM_FILTER_SIZE = 36000
MAX_HASH_FUNCS = 50
UPDATE_NONE = 0
UPDATE_ALL = 1
UPDATE_P2PUBKEY_ONLY = 2
UPDATE_MASK = 3
def __init__(self, nElements, nFPRate, nTweak, nFlags):
"""Create a new bloom filter
The filter will have a given false-positive rate when filled with the
given number of elements.
Note that if the given parameters will result in a filter outside the
bounds of the protocol limits, the filter created will be as close to
the given parameters as possible within the protocol limits. This will
apply if nFPRate is very low or nElements is unreasonably high.
nTweak is a constant which is added to the seed value passed to the
hash function It should generally always be a random value (and is
largely only exposed for unit testing)
nFlags should be one of the UPDATE_* enums (but not _MASK)
"""
LN2SQUARED = 0.4804530139182014246671025263266649717305529515945455
LN2 = 0.6931471805599453094172321214581765680755001343602552
self.vData = bytearray(int(min(-1 / LN2SQUARED * nElements * math.log(nFPRate), self.MAX_BLOOM_FILTER_SIZE * 8) / 8))
self.nHashFuncs = int(min(len(self.vData) * 8 / nElements * LN2, self.MAX_HASH_FUNCS))
self.nTweak = nTweak
self.nFlags = nFlags
def bloom_hash(self, nHashNum, vDataToHash):
return MurmurHash3(((nHashNum * 0xFBA4C795) + self.nTweak) & 0xFFFFFFFF, vDataToHash) % (len(self.vData) * 8)
__bit_mask = bytearray([0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80])
def insert(self, elem):
"""Insert an element in the filter.
elem may be a COutPoint or bytes
"""
if isinstance(elem, bitcoin.core.COutPoint):
elem = elem.serialize()
if len(self.vData) == 1 and self.vData[0] == 0xff:
return
for i in range(0, self.nHashFuncs):
nIndex = self.bloom_hash(i, elem)
# Sets bit nIndex of vData
self.vData[nIndex >> 3] |= self.__bit_mask[7 & nIndex]
def contains(self, elem):
"""Test if the filter contains an element
elem may be a COutPoint or bytes
"""
if isinstance(elem, bitcoin.core.COutPoint):
elem = elem.serialize()
if len(self.vData) == 1 and self.vData[0] == 0xff:
return True
for i in range(0, self.nHashFuncs):
nIndex = self.bloom_hash(i, elem)
if not (self.vData[nIndex >> 3] & self.__bit_mask[7 & nIndex]):
return False
return True
def IsWithinSizeConstraints(self):
return len(self.vData) <= self.MAX_BLOOM_FILTER_SIZE and self.nHashFuncs <= self.MAX_HASH_FUNCS
def IsRelevantAndUpdate(tx, tx_hash):
# Not useful for a client, so not implemented yet.
raise NotImplementedError
__struct = struct.Struct(b'