Encode one item of a BTC witness script
    Return the encoded item (as a string)

    Returns a byte string with the encoded unit

    Based on code from pybitcointools (https://github.com/vbuterin/pybitcointools)
    by Vitalik Buterin
976041
def _btc_witness_serialize_unit(unit):
    
    
    if isinstance(unit, int):
        # pass literal
        return encoding.from_int_to_byte(unit)

    elif unit is None:
        # None means OP_0
        return b'\x00'

    else:
        # return as a varint-prefixed string
        return make_var_string(unit)
393967
def encode(self, b64=False, always_bytes=True):
        """"""
        if self.binary and not b64:
            encoded_packet = six.int2byte(self.packet_type)
        else:
            encoded_packet = six.text_type(self.packet_type)
            if self.binary and b64:
                encoded_packet = 'b' + encoded_packet
        if self.binary:
            if b64:
                encoded_packet += base64.b64encode(self.data).decode('utf-8')
            else:
                encoded_packet += self.data
        elif isinstance(self.data, six.string_types):
            encoded_packet += self.data
        elif isinstance(self.data, dict) or isinstance(self.data, list):
            encoded_packet += self.json.dumps(self.data,
                                              separators=(',', ':'))
        elif self.data is not None:
            encoded_packet += str(self.data)
        if always_bytes and not isinstance(encoded_packet, binary_types):
            encoded_packet = encoded_packet.encode('utf-8')
        return encoded_packet
10344
def encode_contents(self):
        

        header = struct.pack("<LL", self.offset, len(self.raw_data))
        return bytearray(header) + self.raw_data
841617
def _encode_item(self, item: str) -> str:
        
        assert item is not None
        if not self.__redis_conf['anonymization']:
            return item
        connection = self.__get_connection()
        salt = connection.get(self.__redis_conf['salt_key'])
        if salt is None:
            salt = create_salt()
            connection.set(self.__redis_conf['salt_key'], salt)
        BlackRed.__release_connection(connection)
        return sha512(salt + item.encode()).hexdigest()
64186
def encode_ber(value, ber_length=0):
    
    if not ber_length:
        if value < 127: # 1 byte case
            return bytearray([value])
        ber_length = 1
        while value >= pow(2, 8*ber_length):
            ber_length += 1
        ber_length += 1


    ber = bytearray(ber_length)
    ber[0] = 127 + ber_length #ber length byte
    for i in range(1, ber_length):
        ber[i] = (value >> (8 * (ber_length - 1 - i))) & 255
    return ber
1911
def bencode(canonical):
    '''
        
    '''
    in_dict = dict(canonical)

    def encode_str(in_str):
        out_str = str(len(in_str)) + ':' + in_str
        return out_str

    def encode_int(in_int):
        out_str = str('i' + str(in_int) + 'e')
        return out_str

    def encode_list(in_list):
        out_str = 'l'
        for item in in_list:
            out_str += encode_item(item)
        else:
            out_str += 'e'
        return out_str

    def encode_dict(in_dict):
        out_str = 'd'
        keys = sorted(in_dict.keys())
        for key in keys:
            val = in_dict[key]
            out_str = out_str + encode_item(key) + encode_item(val)
        else:
            out_str += 'e'
        return out_str

    def encode_item(x):
        if isinstance(x, str):
            return encode_str(x)
        elif isinstance(x, int):
            return encode_int(x)
        elif isinstance(x, list):
            return encode_list(x)
        elif isinstance(x, dict):
            return encode_dict(x)

    return encode_item(in_dict)
146486
def data_from_base58(string)
      raise ArgumentError, "String is missing" if !string
      int = int_from_base58(string)
      bytes = []
      while int > 0
        remainder = int % 256
        int = int / 256
        bytes.unshift(remainder)
      end
      data = BTC::Data.data_from_bytes(bytes)
      byte_for_1 = "1".bytes.first
      BTC::Data.ensure_ascii_compatible_encoding(string).bytes.each do |byte|
        break if byte != byte_for_1
        data = "\x00" + data
      end
      data
    end
374770
def encode(cls, s):
        
        b = ByteString(s)
        be = base64.b64encode(b).strip()
        return String(be)
399676
def btc_script_to_hex(script):
    

    hex_script = ''
    parts = script.split(' ')
    for part in parts:
        if part[0:3] == 'OP_':
            value = OPCODE_VALUES.get(part)
            if not value:
                raise ValueError("Unrecognized opcode {}".format(part))

            hex_script += "%0.2x" % value

        elif hashing.is_hex(part):
            hex_script += '%0.2x' % hashing.count_bytes(part) + part

        else:
            raise Exception('Invalid script - only opcodes and hex characters allowed.')

    return hex_script
215721
def btc_make_data_script( data, **ignored ):
    
    if len(data) >= MAX_DATA_LEN * 2:
        raise ValueError("Data hex string is too long")     # note: data is a hex string

    if len(data) % 2 != 0:
        raise ValueError("Data hex string is not even length")

    return "6a{:02x}{}".format(len(data)/2, data)
1000362
def encode (self):
    """"""
    byte = self.default

    for bit, name, value0, value1, default in SeqCmdAttrs.Table:
      if name in self.attrs:
        value = self.attrs[name]
        byte  = setBit(byte, bit, value == value1)

    return struct.pack('B', byte)
797099
def btc_script_hex_to_address( script_hex, segwit=None ):
    
    # TODO: make this support more than bitcoin-like scripts
    if script_hex.startswith("76a914") and script_hex.endswith("88ac") and len(script_hex) == 50:
        # p2pkh script
        hash160_bin = binascii.unhexlify(script_hex[6:-4])
        return bin_hash160_to_address(hash160_bin, version_byte=version_byte)

    elif script_hex.startswith("a914") and script_hex.endswith("87") and len(script_hex) == 46:
        # p2sh script
        hash160_bin = binascii.unhexlify(script_hex[4:-2])
        return bin_hash160_to_address(hash160_bin, version_byte=multisig_version_byte)

    elif script_hex.startswith('0014') and len(script_hex) == 44:
        # p2wpkh script (bech32 address)
        hash160_bin = binascii.unhexlify(script_hex[4:])
        return segwit_addr_encode(hash160_bin) 

    elif script_hex.startswith('0020') and len(script_hex) == 68:
        # p2wsh script (bech32 address)
        sha256_bin = binascii.unhexlify(script_hex[4:])
        return segwit_addr_encode(sha256_bin)

    return None
469902
def encode(self):
        
        ret = bytearray()
        for name, len, typecode in self.format:
            value = getattr(self, name)
            buf = struct.pack('<' + typecode, value)
            ret.extend(buf)
        return bytes(ret)
1031620
def from_bytes(TxIn, byte_string):
        '''
        
        '''
        outpoint = Outpoint.from_bytes(byte_string[:36])

        script_sig_len = VarInt.from_bytes(byte_string[36:45])
        script_start = 36 + len(script_sig_len)
        script_end = script_start + script_sig_len.number
        script_sig = byte_string[script_start:script_end]

        sequence = byte_string[script_end:script_end + 4]
        if script_sig == b'':
            stack_script = b''
            redeem_script = b''
        else:
            stack_script, redeem_script = TxIn._parse_script_sig(script_sig)
        return TxIn(
            outpoint=outpoint,
            stack_script=stack_script,
            redeem_script=redeem_script,
            sequence=sequence)
550701
def decodepackbits(encoded):
    
    func = ord if sys.version[0] == '2' else lambda x: x
    result = []
    i = 0
    try:
        while True:
            n = func(encoded[i]) + 1
            i += 1
            if n < 129:
                result.extend(encoded[i:i+n])
                i += n
            elif n > 129:
                result.extend(encoded[i:i+1] * (258-n))
                i += 1
    except IndexError:
        pass
    return b''.join(result) if sys.version[0] == '2' else bytes(result)
72504
def btc_tx_serialize(_txobj):
    
    
    # output buffer
    o = []
    txobj = None
    if encoding.json_is_base(_txobj, 16):
        # txobj is built from hex strings already.  deserialize them 
        txobj = encoding.json_changebase(_txobj, lambda x: binascii.unhexlify(x))
    else:
        txobj = copy.deepcopy(_txobj)

    # version
    o.append(encoding.encode(txobj["version"], 256, 4)[::-1])

    # do we have any witness scripts?
    have_witness = False
    for inp in txobj['ins']:
        if inp.has_key('witness_script') and len(inp['witness_script']) > 0:
            have_witness = True
            break

    if have_witness:
        # add segwit marker 
        o.append('\x00\x01')
    
    # number of inputs
    o.append(encoding.num_to_var_int(len(txobj["ins"])))

    # all inputs
    for inp in txobj["ins"]:
        # input tx hash
        o.append(inp["outpoint"]["hash"][::-1])

        # input tx outpoint
        o.append(encoding.encode(inp["outpoint"]["index"], 256, 4)[::-1])

        # input scriptsig
        script = inp.get('script')
        if not script:
            script = bytes()

        scriptsig = encoding.num_to_var_int(len(script)) + script
        o.append(scriptsig)

        # sequence
        o.append(encoding.encode(inp.get("sequence", UINT_MAX - 1), 256, 4)[::-1])

    # number of outputs
    o.append(encoding.num_to_var_int(len(txobj["outs"])))

    # all outputs
    for out in txobj["outs"]:
        # value
        o.append(encoding.encode(out["value"], 256, 8)[::-1])

        # scriptPubKey
        scriptpubkey = encoding.num_to_var_int(len(out['script'])) + out['script']
        o.append(scriptpubkey)

    # add witnesses 
    if have_witness:
        for inp in txobj['ins']:
            witness_script = inp.get('witness_script')
            if not witness_script:
                witness_script = '\x00'

            o.append(witness_script)

    # locktime
    o.append(encoding.encode(txobj["locktime"], 256, 4)[::-1])

    # full string
    ret = ''.join( encoding.json_changebase(o, lambda x: encoding.safe_hexlify(x)) )
    return ret
1005988
def btc_tx_make_input_signature_segwit(tx, idx, prevout_amount, prevout_script, privkey_str, hashcode):
    
    # always compressed
    if len(privkey_str) == 64:
        privkey_str += '01'

    pk = ecdsalib.ecdsa_private_key(str(privkey_str))
    pubk = pk.public_key()
    
    priv = pk.to_hex()

    # must always be compressed
    pub = keylib.key_formatting.compress(pubk.to_hex())
    sighash = btc_tx_sighash_segwit(tx, idx, prevout_amount, prevout_script, hashcode=hashcode)
    
    # sign using uncompressed private key
    # pk_uncompressed_hex, pubk_uncompressed_hex = ecdsalib.get_uncompressed_private_and_public_keys(priv)
    sigb64 = ecdsalib.sign_digest( sighash, priv )

    # sanity check 
    # assert ecdsalib.verify_digest( txhash, pubk_uncompressed_hex, sigb64 )

    sig_r, sig_s = ecdsalib.decode_signature(sigb64)
    sig_bin = btc_tx_der_encode_signature(sig_r, sig_s)
    sig = sig_bin.encode('hex') + encoding.encode(hashcode, 16, 2)

    # print 'segwit signature: {}'.format(sig)
    return sig