Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion bitcoin/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
# propagated, or distributed except according to the terms contained in the
# LICENSE file.

from __future__ import absolute_import, division, print_function, unicode_literals

import bitcoin.core

Expand Down
18 changes: 3 additions & 15 deletions bitcoin/base58.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,6 @@

"""Base58 encoding and decoding"""

from __future__ import absolute_import, division, print_function, unicode_literals

import sys
_bchr = chr
_bord = ord
if sys.version > '3':
long = int
_bchr = lambda x: bytes([x])
_bord = lambda x: x

import binascii

Expand Down Expand Up @@ -52,10 +43,7 @@ def encode(b):
res = ''.join(res[::-1])

# Encode leading zeros as base58 zeros
czero = b'\x00'
if sys.version > '3':
# In Python3 indexing a bytes returns numbers, not characters.
czero = 0
czero = 0
pad = 0
for c in b:
if c == czero:
Expand Down Expand Up @@ -108,7 +96,7 @@ def __new__(cls, s):
if check0 != check1:
raise Base58ChecksumError('Checksum mismatch: expected %r, calculated %r' % (check0, check1))

return cls.from_bytes(data, _bord(verbyte[0]))
return cls.from_bytes(data, verbyte[0])

def __init__(self, s):
"""Initialize from base58-encoded string
Expand Down Expand Up @@ -138,7 +126,7 @@ def to_bytes(self):

def __str__(self):
"""Convert to string"""
vs = _bchr(self.nVersion) + self
vs = bytes([self.nVersion]) + self
check = bitcoin.core.Hash(vs)[0:4]
return encode(vs + check)

Expand Down
8 changes: 0 additions & 8 deletions bitcoin/bech32.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,6 @@

"""Bech32 encoding and decoding"""

import sys
_bchr = chr
_bord = ord
if sys.version > '3':
long = int
_bchr = lambda x: bytes([x])
_bord = lambda x: x

from bitcoin.segwit_addr import encode, decode
import bitcoin

Expand Down
18 changes: 4 additions & 14 deletions bitcoin/bloom.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,8 @@

"""Bloom filter support"""

from __future__ import absolute_import, division, print_function, unicode_literals

import struct
import sys
import math

import bitcoin.core
Expand Down Expand Up @@ -56,16 +54,12 @@ def MurmurHash3(nHashSeed, vDataToHash):
# tail
k1 = 0
j = (len(vDataToHash) // 4) * 4
bord = ord
if sys.version > '3':
# In Py3 indexing bytes returns numbers, not characters
bord = lambda x: x
if len(vDataToHash) & 3 >= 3:
k1 ^= bord(vDataToHash[j+2]) << 16
k1 ^= vDataToHash[j+2] << 16
if len(vDataToHash) & 3 >= 2:
k1 ^= bord(vDataToHash[j+1]) << 8
k1 ^= vDataToHash[j+1] << 8
if len(vDataToHash) & 3 >= 1:
k1 ^= bord(vDataToHash[j])
k1 ^= vDataToHash[j]

k1 &= 0xFFFFFFFF
k1 = (k1 * c1) & 0xFFFFFFFF
Expand Down Expand Up @@ -180,11 +174,7 @@ def stream_deserialize(cls, f):
return deserialized

def stream_serialize(self, f):
if sys.version > '3':
bitcoin.core.serialize.BytesSerializer.stream_serialize(self.vData, f)
else:
# 2.7 has problems with f.write(bytearray())
bitcoin.core.serialize.BytesSerializer.stream_serialize(bytes(self.vData), f)
bitcoin.core.serialize.BytesSerializer.stream_serialize(self.vData, f)
f.write(self.__struct.pack(self.nHashFuncs, self.nTweak, self.nFlags))

__all__ = (
Expand Down
48 changes: 3 additions & 45 deletions bitcoin/core/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,28 +9,22 @@
# propagated, or distributed except according to the terms contained in the
# LICENSE file.

from __future__ import absolute_import, division, print_function

import binascii
import struct
import sys
import time

from .script import CScript, CScriptWitness, CScriptOp, OP_RETURN
from . import script
from .script import CScript, CScriptWitness, OP_RETURN

from .serialize import *

if sys.version > '3':
_bytes = bytes
else:
_bytes = lambda x: bytes(bytearray(x))

# Core definitions
COIN = 100000000
MAX_BLOCK_SIZE = 1000000
MAX_BLOCK_WEIGHT = 4000000
MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50
WITNESS_COINBASE_SCRIPTPUBKEY_MAGIC = _bytes([OP_RETURN, 0x24, 0xaa, 0x21, 0xa9, 0xed])
WITNESS_COINBASE_SCRIPTPUBKEY_MAGIC = bytes([OP_RETURN, 0x24, 0xaa, 0x21, 0xa9, 0xed])

def MoneyRange(nValue, params=None):
global coreparams
Expand All @@ -39,30 +33,14 @@ def MoneyRange(nValue, params=None):

return 0 <= nValue <= params.MAX_MONEY

def _py2_x(h):
"""Convert a hex string to bytes"""
return binascii.unhexlify(h)

def x(h):
"""Convert a hex string to bytes"""
return binascii.unhexlify(h.encode('utf8'))

def _py2_b2x(b):
"""Convert bytes to a hex string"""
return binascii.hexlify(b)

def b2x(b):
"""Convert bytes to a hex string"""
return binascii.hexlify(b).decode('utf8')

def _py2_lx(h):
"""Convert a little-endian hex string to bytes

Lets you write uint256's and uint160's the way the Satoshi codebase shows
them.
"""
return binascii.unhexlify(h)[::-1]

def lx(h):
"""Convert a little-endian hex string to bytes

Expand All @@ -71,14 +49,6 @@ def lx(h):
"""
return binascii.unhexlify(h.encode('utf8'))[::-1]

def _py2_b2lx(b):
"""Convert bytes to a little-endian hex string

Lets you show uint256's and uint160's the way the Satoshi codebase shows
them.
"""
return binascii.hexlify(b[::-1])

def b2lx(b):
"""Convert bytes to a little-endian hex string

Expand All @@ -87,18 +57,6 @@ def b2lx(b):
"""
return binascii.hexlify(b[::-1]).decode('utf8')

if not (sys.version > '3'):
x = _py2_x
b2x = _py2_b2x
lx = _py2_lx
b2lx = _py2_b2lx

del _py2_x
del _py2_b2x
del _py2_lx
del _py2_b2lx


def str_money_value(value):
"""Convert an integer money value to a fixed point string"""
r = '%i.%08i' % (value // COIN, value % COIN)
Expand Down
1 change: 0 additions & 1 deletion bitcoin/core/_bignum.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
#
# Internally used for script evaluation; not to be used externally.

from __future__ import absolute_import, division, print_function, unicode_literals

import struct

Expand Down
18 changes: 3 additions & 15 deletions bitcoin/core/key.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,10 @@
import ctypes
import ctypes.util
import hashlib
import sys
from os import urandom
import bitcoin
import bitcoin.signature

_bchr = chr
_bord = ord
if sys.version > '3':
_bchr = lambda x: bytes([x])
_bord = lambda x: x

import bitcoin.core.script

_ssl = ctypes.cdll.LoadLibrary(
Expand Down Expand Up @@ -587,8 +580,8 @@ def recover_compact(cls, hash, sig): # pylint: disable=redefined-builtin
if len(sig) != 65:
raise ValueError("Signature should be 65 characters, not [%d]" % (len(sig), ))

recid = (_bord(sig[0]) - 27) & 3
compressed = (_bord(sig[0]) - 27) & 4 != 0
recid = (sig[0] - 27) & 3
compressed = (sig[0] - 27) & 4 != 0

cec_key = CECKey()
cec_key.set_compressed(compressed)
Expand Down Expand Up @@ -620,12 +613,7 @@ def __str__(self):
return repr(self)

def __repr__(self):
# Always have represent as b'<secret>' so test cases don't have to
# change for py2/3
if sys.version > '3':
return '%s(%s)' % (self.__class__.__name__, super(CPubKey, self).__repr__())
else:
return '%s(b%s)' % (self.__class__.__name__, super(CPubKey, self).__repr__())
return '%s(%s)' % (self.__class__.__name__, super(CPubKey, self).__repr__())

__all__ = (
'CECKey',
Expand Down
46 changes: 18 additions & 28 deletions bitcoin/core/script.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,8 @@
is in bitcoin.core.scripteval
"""

from __future__ import absolute_import, division, print_function

import sys
_bchr = chr
_bord = ord
if sys.version > '3':
long = int
_bchr = lambda x: bytes([x])
_bord = lambda x: x
from io import BytesIO as _BytesIO
else:
from cStringIO import StringIO as _BytesIO

from io import BytesIO

import struct

Expand All @@ -50,9 +40,9 @@ class CScriptOp(int):
def encode_op_pushdata(d):
"""Encode a PUSHDATA op, returning bytes"""
if len(d) < 0x4c:
return b'' + _bchr(len(d)) + d # OP_PUSHDATA
return bytes([len(d)]) + d # OP_PUSHDATA
elif len(d) <= 0xff:
return b'\x4c' + _bchr(len(d)) + d # OP_PUSHDATA1
return b'\x4c' + bytes([len(d)]) + d # OP_PUSHDATA1
elif len(d) <= 0xffff:
return b'\x4d' + struct.pack(b'<H', len(d)) + d # OP_PUSHDATA2
elif len(d) <= 0xffffffff:
Expand Down Expand Up @@ -524,12 +514,12 @@ class CScript(bytes):
def __coerce_instance(cls, other):
# Coerce other into bytes
if isinstance(other, CScriptOp):
other = _bchr(other)
elif isinstance(other, (int, long)):
other = bytes([other])
elif isinstance(other, int):
if 0 <= other <= 16:
other = bytes(_bchr(CScriptOp.encode_op_n(other)))
other = bytes([CScriptOp.encode_op_n(other)])
elif other == -1:
other = bytes(_bchr(OP_1NEGATE))
other = bytes([OP_1NEGATE])
else:
other = CScriptOp.encode_op_pushdata(bitcoin.core._bignum.bn2vch(other))
elif isinstance(other, (bytes, bytearray)):
Expand Down Expand Up @@ -572,7 +562,7 @@ def raw_iter(self):
i = 0
while i < len(self):
sop_idx = i
opcode = _bord(self[i])
opcode = self[i]
i += 1

if opcode > OP_PUSHDATA4:
Expand All @@ -588,21 +578,21 @@ def raw_iter(self):
pushdata_type = 'PUSHDATA1'
if i >= len(self):
raise CScriptInvalidError('PUSHDATA1: missing data length')
datasize = _bord(self[i])
datasize = self[i]
i += 1

elif opcode == OP_PUSHDATA2:
pushdata_type = 'PUSHDATA2'
if i + 1 >= len(self):
raise CScriptInvalidError('PUSHDATA2: missing data length')
datasize = _bord(self[i]) + (_bord(self[i+1]) << 8)
datasize = self[i] + (self[i+1] << 8)
i += 2

elif opcode == OP_PUSHDATA4:
pushdata_type = 'PUSHDATA4'
if i + 3 >= len(self):
raise CScriptInvalidError('PUSHDATA4: missing data length')
datasize = _bord(self[i]) + (_bord(self[i+1]) << 8) + (_bord(self[i+2]) << 16) + (_bord(self[i+3]) << 24)
datasize = self[i] + (self[i+1] << 8) + (self[i+2] << 16) + (self[i+3] << 24)
i += 4

else:
Expand Down Expand Up @@ -676,9 +666,9 @@ def is_p2sh(self):
Note that this test is consensus-critical.
"""
return (len(self) == 23 and
_bord(self[0]) == OP_HASH160 and
_bord(self[1]) == 0x14 and
_bord(self[22]) == OP_EQUAL)
self[0] == OP_HASH160 and
self[1] == 0x14 and
self[22] == OP_EQUAL)

def is_witness_scriptpubkey(self):
"""Returns true if this is a scriptpubkey signaling segregated witness data.
Expand Down Expand Up @@ -747,7 +737,7 @@ def has_canonical_pushes(self):
if op > OP_16:
continue

elif op < OP_PUSHDATA1 and op > OP_0 and len(data) == 1 and _bord(data[0]) <= 16:
elif op < OP_PUSHDATA1 and op > OP_0 and len(data) == 1 and data[0] <= 16:
# Could have used an OP_n code, rather than a 1-byte push.
return False

Expand All @@ -770,7 +760,7 @@ def has_canonical_pushes(self):
def is_unspendable(self):
"""Test if the script is provably unspendable"""
return (len(self) > 0 and
_bord(self[0]) == OP_RETURN)
self[0] == OP_RETURN)

def is_valid(self):
"""Return True if the script is valid, False otherwise
Expand Down Expand Up @@ -1018,7 +1008,7 @@ def SignatureHash(script, txTo, inIdx, hashtype, amount=None, sigversion=SIGVERS
serialize_outputs = txTo.vout[inIdx].serialize()
hashOutputs = bitcoin.core.Hash(serialize_outputs)

f = _BytesIO()
f = BytesIO()
f.write(struct.pack("<i", txTo.nVersion))
f.write(hashPrevouts)
f.write(hashSequence)
Expand Down
Loading