def create_contract(db, block, tx, msg):
    if len(msg.sender) == 40:   # Sender is contract.
        sender = binascii.unhexlify(msg.sender)
    else:                       # Sender is regular address.
        sender = script.base58_check_decode(msg.sender, config.ADDRESSVERSION)

    if tx.sender != msg.sender:
        block.increment_nonce(msg.sender)
    nonce = utils.encode_int(block.get_nonce(msg.sender) - 1)
    # msg.to = utils.sha3(rlp.encode([sender, nonce]))[12:].encode('hex')
    msg.to = utils.contract_sha3(rlp.encode([sender, nonce]))
    assert not block.get_code(msg.to)

    res, gas, dat = apply_msg(db, block, tx, msg, msg.data)
    if res:
        cursor = db.cursor()
        bindings = {'contract_id': msg.to, 'tx_index': tx.tx_index, 'tx_hash': tx.tx_hash, 'block_index': block.number, 'source': tx.sender, 'code': bytes(dat), 'nonce': nonce}
        sql = '''INSERT INTO contracts VALUES (:contract_id, :tx_index, :tx_hash, :block_index, :source, :code, :nonce)'''
        cursor.execute(sql, bindings)
        return msg.to, gas, dat
    else:
        if tx.sender != msg.sender:
            block.decrement_nonce(msg.sender)
        block.del_account(msg.to)
        return res, gas, dat
def get_monosig_script(address):

    # Construct script.
    pubkeyhash = script.base58_check_decode(address, config.ADDRESSVERSION)
    tx_script = OP_DUP                                     # OP_DUP
    tx_script += OP_HASH160                                # OP_HASH160
    tx_script += op_push(20)                               # Push 0x14 bytes
    tx_script += pubkeyhash                                # pubKeyHash
    tx_script += OP_EQUALVERIFY                            # OP_EQUALVERIFY
    tx_script += OP_CHECKSIG                               # OP_CHECKSIG

    return tx_script
    def get_address(scriptpubkey):
        pubkeyhash = get_pubkeyhash(scriptpubkey)
        if not pubkeyhash:
            return False
        pubkeyhash = binascii.hexlify(pubkeyhash).decode('utf-8')
        address = script.base58_check_encode(pubkeyhash, config.ADDRESSVERSION)
        # Test decoding of address.
        if address != config.UNSPENDABLE and binascii.unhexlify(bytes(pubkeyhash, 'utf-8')) != script.base58_check_decode(address, config.ADDRESSVERSION):
            return False

        return address