Ejemplo n.º 1
0
def make_multisig_info( m, pks ):
    """
    Make a multisig address and redeem script.
    @m of the given @pks must sign.
    Return {'address': p2sh address, 'redeem_script': redeem script, 'private_keys': private keys}
    Return (p2sh address, redeem script)
    """

    pubs = []
    privkeys = []
    for pk in pks:
        priv = BitcoinPrivateKey(pk)
        priv_wif = priv.to_wif()
        pub = priv.public_key().to_hex()

        privkeys.append(priv_wif)
        pubs.append(pub)

    script = bitcoin.mk_multisig_script( pubs, m )
    addr = bitcoin.p2sh_scriptaddr(script, multisig_version_byte)

    return {
        'address': addr,
        'redeem_script': script,
        'private_keys': privkeys
    }
Ejemplo n.º 2
0
def make_multisig_info( m, pks ):
    """
    Make a multisig address and redeem script.
    @m of the given @pks must sign.
    Return {'address': p2sh address, 'redeem_script': redeem script, 'private_keys': private keys}
    Return (p2sh address, redeem script)
    """

    pubs = []
    privkeys = []
    for pk in pks:
        priv = BitcoinPrivateKey(pk)
        priv_hex = priv.to_hex()
        pub_hex = priv.public_key().to_hex()

        privkeys.append(priv_hex)
        pubs.append(pub_hex)

    script = bitcoin.mk_multisig_script( pubs, m )
    addr = bitcoin.p2sh_scriptaddr(script, multisig_version_byte)

    return {
        'address': addr,
        'redeem_script': script,
        'private_keys': privkeys
    }
Ejemplo n.º 3
0
def compute_adr_P2SH(args):
    try:
        (priv_num, pubs, nkr, nkt) = args
        pub = bitcoin.privtopub(hexa(priv_num))
        mscript = bitcoin.mk_multisig_script([pub] + pubs[1:], nkr, nkt)
        return bitcoin.p2sh_scriptaddr(mscript)
    except KeyboardInterrupt:
        return "x"
Ejemplo n.º 4
0
def compute_adr_P2SH(args):
    try:
        (priv_num, pubs, nkr, nkt) = args
        pub = coincurve.PrivateKey.from_int(priv_num).public_key.format(
            False).encode('hex')
        mscript = bitcoin.mk_multisig_script([pub] + pubs[1:], nkr, nkt)
        return bitcoin.p2sh_scriptaddr(mscript)
    except:
        return "x"
Ejemplo n.º 5
0
def pkvkey2adrw(pvkey, network=5):
    pub_hex = bitcoin.privtopub(pvkey)
    pub_bin = bitcoin.encode_pubkey(pub_hex, "bin_compressed")
    PKH = bitcoin.bin_hash160(pub_bin)
    script = "\0\x14" + PKH
    address_bin = bitcoin.bin_hash160(script)
    address = bitcoin.bin_to_b58check(address_bin, network)
    assert bitcoin.p2sh_scriptaddr(script, network) == address
    return address
Ejemplo n.º 6
0
def bitcoin_address(digest):
    bitcoin_keys = [
        '\x02\xc0T!\xaa\x00\x13\xee\xd38T#\xb6<\xd2\x89' +
        '\xc3BR\x118\xaa\xffj\x91U\xb3\xc7\xc8t\xc3\x1e\xa9',
        '\x03\xb3\xb1|\xe2\x13\xe4\xed\xb9\xf1\x7f\x0e\x11' +
        '\xf5h\x80\xa8\x96r\xd2 4\x83\xbb\x7fu\xb1\x1a%_\x08\xdc\x96'
    ]
    script = bitcoin.serialize_script([digest, 117, 2] + bitcoin_keys +
                                      [2, 174])
    return bitcoin.p2sh_scriptaddr(script)
Ejemplo n.º 7
0
 def _bake(self):
     self.privates = [
         hashlib.sha256('priv{}'.format(i).encode()).hexdigest() + '01'
         for i in range(0, 18)
     ]
     self._scripts = [
         bitcoin.mk_multisig_script(bitcoin.privtopub(self.privates[x]),
                                    bitcoin.privtopub(self.privates[x + 1]),
                                    bitcoin.privtopub(self.privates[x + 2]),
                                    2) for x in range(0, 18, 3)
     ]
     self.addresses = [
         bitcoin.p2sh_scriptaddr(script, magicbyte=196)
         for script in self._scripts
     ]
def make_multisig_info(m, pks):
    """
    Make a multisig address and redeem script
    """

    pubs = []
    prikeys = []
    for pk in pks:
        priv = BitcoinPrivateKey(pk)
        priv_wif = priv.to_wif()
        pub = priv.public_key().to_hex()

        prikeys.append(priv_wif)
        pubs.append(pub)

    script = bitcoin.mk_multisig_script( pubs, m)
    addr = bitcoin.p2sh_scriptaddr(script, multisig_version_byte)

    return {
        'address': addr,
        'redeem_script': script,
        'private_keys': prikeys
    }
Ejemplo n.º 9
0
def make_p2sh_address(script):
    """
    Make a P2SH address
    """
    addr = bitcoin.p2sh_scriptaddr(script, multisig_version_byte)
    return addr
Ejemplo n.º 10
0
def make_multisig_address( redeem_script ):
    """
    Make a multisig address (p2sh address)
    """
    return bitcoin.p2sh_scriptaddr( redeem_script, multisig_version_byte )
Ejemplo n.º 11
0
def make_multisig_address( redeem_script ):
    """
    Make a multisig address (p2sh address)
    """
    return bitcoin.p2sh_scriptaddr( redeem_script, multisig_version_byte )
Ejemplo n.º 12
0
    def add_purchase_info(self,
                          quantity,
                          ship_to=None,
                          shipping_address=None,
                          city=None,
                          state=None,
                          postal_code=None,
                          country=None,
                          moderator=None,
                          options=None):
        """
        Update the contract with the buyer's purchase information.
        """

        profile = Profile(self.db).get()
        order_json = {
            "buyer_order": {
                "order": {
                    "ref_hash":
                    digest(json.dumps(self.contract, indent=4)).encode("hex"),
                    "quantity":
                    quantity,
                    "id": {
                        "guid": self.keychain.guid.encode("hex"),
                        "pubkeys": {
                            "guid":
                            self.keychain.guid_signed_pubkey[64:].encode(
                                "hex"),
                            "bitcoin":
                            bitcoin.bip32_extract_key(
                                self.keychain.bitcoin_master_pubkey),
                            "encryption":
                            self.keychain.encryption_pubkey.encode("hex")
                        }
                    },
                    "payment": {}
                }
            }
        }
        if profile.HasField("handle"):
            order_json["buyer_order"]["order"]["id"][
                "blockchain_id"] = profile.handle
        if self.contract["vendor_offer"]["listing"]["metadata"][
                "category"] == "physical good":
            order_json["buyer_order"]["order"]["shipping"] = {}
            order_json["buyer_order"]["order"]["shipping"]["ship_to"] = ship_to
            order_json["buyer_order"]["order"]["shipping"][
                "address"] = shipping_address
            order_json["buyer_order"]["order"]["shipping"]["city"] = city
            order_json["buyer_order"]["order"]["shipping"]["state"] = state
            order_json["buyer_order"]["order"]["shipping"][
                "postal_code"] = postal_code
            order_json["buyer_order"]["order"]["shipping"]["country"] = country
        if options is not None:
            order_json["buyer_order"]["order"]["options"] = options
        if moderator:  # TODO: Handle direct payments
            chaincode = sha256(str(
                random.getrandbits(256))).digest().encode("hex")
            order_json["buyer_order"]["order"]["payment"][
                "chaincode"] = chaincode
            valid_mod = False
            for mod in self.contract["vendor_offer"]["listing"]["moderators"]:
                if mod["guid"] == moderator:
                    order_json["buyer_order"]["order"]["moderator"] = moderator
                    masterkey_m = mod["pubkeys"]["bitcoin"]["key"]
                    valid_mod = True
            if not valid_mod:
                return False
            masterkey_b = bitcoin.bip32_extract_key(
                self.keychain.bitcoin_master_pubkey)
            masterkey_v = self.contract["vendor_offer"]["listing"]["id"][
                "pubkeys"]["bitcoin"]
            buyer_key = derive_childkey(masterkey_b, chaincode)
            vendor_key = derive_childkey(masterkey_v, chaincode)
            moderator_key = derive_childkey(masterkey_m, chaincode)

            redeem_script = bitcoin.mk_multisig_script(
                [buyer_key, vendor_key, moderator_key], 2)
            order_json["buyer_order"]["order"]["payment"][
                "redeem_script"] = redeem_script
            if self.testnet:
                payment_address = bitcoin.p2sh_scriptaddr(redeem_script, 196)
            else:
                payment_address = bitcoin.p2sh_scriptaddr(redeem_script)
            order_json["buyer_order"]["order"]["payment"][
                "address"] = payment_address

        price_json = self.contract["vendor_offer"]["listing"]["item"][
            "price_per_unit"]
        if "bitcoin" in price_json:
            order_json["buyer_order"]["order"]["payment"][
                "amount"] = price_json["bitcoin"]
        else:
            currency_code = price_json["fiat"]["currency_code"]
            fiat_price = price_json["fiat"]["price"]
            try:
                request = Request('https://api.bitcoinaverage.com/ticker/' +
                                  currency_code.upper() + '/last')
                response = urlopen(request)
                conversion_rate = response.read()
            except URLError:
                return False
            order_json["buyer_order"]["order"]["payment"]["amount"] = float(
                "{0:.8f}".format(float(fiat_price) / float(conversion_rate)))

        self.contract["buyer_order"] = order_json["buyer_order"]
        order = json.dumps(self.contract["buyer_order"]["order"], indent=4)
        # TODO: This should also be signed with the bitcoin key. It's the only way a moderator
        # will have to link this contract to a bitcoin transaction.
        self.contract["buyer_order"]["signature"] = \
            self.keychain.signing_key.sign(order, encoder=nacl.encoding.HexEncoder)[:128]
        return (self.contract["buyer_order"]["order"]["payment"]["address"],
                order_json["buyer_order"]["order"]["payment"]["amount"])
Ejemplo n.º 13
0
         P2SH = True
 except:
     raise ValueError(
         "Error in arguments\nUse :     SigVanity.py [ <1xFirstBits> |\nm (<KeysReq> <KeysTot>) |\n<3xFirstBits> (<KeysReq> <KeysTot>) [<PubKeyHex> [<PubKeyHex> ...]]\n]"
     )
 load_gtable('lib/G_Table')
 if P2SH:
     privs = [randomforkey() for x in range(nkeystotal - npubinput)]
     pubs = [bitcoin.privtopub(hexa(priv)) for priv in privs]
     pubinputlist = []
     for item in rawpubinputlist:
         pubinputlist.append(item.lower())
     pubs = pubs + pubinputlist
     addresses = [bitcoin.pubtoaddr(pub) for pub in pubs]
     mscript = bitcoin.mk_multisig_script(pubs, nkeysneeded, nkeystotal)
     address = bitcoin.p2sh_scriptaddr(mscript)
     foundprivkeynum = privs[0]
 else:
     privkeynum = randomforkey()
     address = compute_adr(privkeynum)
     foundprivkeynum = privkeynum
 if vanity:
     address = None
     if P2SH:
         newprivkeynum = privs[0]
         print "\nVanity Mode, please Wait ..."
         print "Press CTRL+C to stop searching"
         nstart = privs[0]
         startTime = time.time()
         try:
             while address == None:
Ejemplo n.º 14
0
    def verify(self, sender_key):
        """
        Validate that an order sent over by a buyer is filled out correctly.
        """

        try:
            contract_dict = json.loads(json.dumps(self.contract, indent=4),
                                       object_pairs_hook=OrderedDict)
            del contract_dict["buyer_order"]
            contract_hash = digest(json.dumps(contract_dict, indent=4))

            ref_hash = unhexlify(
                self.contract["buyer_order"]["order"]["ref_hash"])

            # verify that the reference hash matches the contract and that the contract actually exists
            if contract_hash != ref_hash or not self.db.HashMap().get_file(
                    ref_hash):
                raise Exception("Order for contract that doesn't exist")

            # verify the signature on the order
            verify_key = nacl.signing.VerifyKey(sender_key)
            verify_key.verify(
                json.dumps(self.contract["buyer_order"]["order"], indent=4),
                unhexlify(self.contract["buyer_order"]["signature"]))

            # TODO: verify the bitcoin signature after we add it

            # verify buyer included the correct bitcoin amount for payment
            price_json = self.contract["vendor_offer"]["listing"]["item"][
                "price_per_unit"]
            if "bitcoin" in price_json:
                asking_price = price_json["bitcoin"]
            else:
                currency_code = price_json["fiat"]["currency_code"]
                fiat_price = price_json["fiat"]["price"]
                request = Request('https://api.bitcoinaverage.com/ticker/' +
                                  currency_code.upper() + '/last')
                response = urlopen(request)
                conversion_rate = response.read()
                asking_price = float("{0:.8f}".format(
                    float(fiat_price) / float(conversion_rate)))
            if asking_price > self.contract["buyer_order"]["order"]["payment"][
                    "amount"]:
                raise Exception("Insuffient Payment")

            # verify a valid moderator was selected
            # TODO: handle direct payments
            valid_mod = False
            for mod in self.contract["vendor_offer"]["listing"]["moderators"]:
                if mod["guid"] == self.contract["buyer_order"]["order"][
                        "moderator"]:
                    valid_mod = True
            if not valid_mod:
                raise Exception("Invalid moderator")

            # verify all the shipping fields exist
            if self.contract["vendor_offer"]["listing"]["metadata"][
                    "category"] == "physical good":
                shipping = self.contract["buyer_order"]["order"]["shipping"]
                keys = [
                    "ship_to", "address", "postal_code", "city", "state",
                    "country"
                ]
                for value in map(shipping.get, keys):
                    if value is None:
                        raise Exception("Missing shipping field")

            # verify buyer ID
            pubkeys = self.contract["buyer_order"]["order"]["id"]["pubkeys"]
            keys = ["guid", "bitcoin", "encryption"]
            for value in map(pubkeys.get, keys):
                if value is None:
                    raise Exception("Missing pubkey field")

            # verify redeem script
            chaincode = self.contract["buyer_order"]["order"]["payment"][
                "chaincode"]
            for mod in self.contract["vendor_offer"]["listing"]["moderators"]:
                if mod["guid"] == self.contract["buyer_order"]["order"][
                        "moderator"]:
                    masterkey_m = mod["pubkeys"]["bitcoin"]["key"]

            masterkey_b = self.contract["buyer_order"]["order"]["id"][
                "pubkeys"]["bitcoin"]
            masterkey_v = bitcoin.bip32_extract_key(
                self.keychain.bitcoin_master_pubkey)
            buyer_key = derive_childkey(masterkey_b, chaincode)
            vendor_key = derive_childkey(masterkey_v, chaincode)
            moderator_key = derive_childkey(masterkey_m, chaincode)

            redeem_script = bitcoin.mk_multisig_script(
                [buyer_key, vendor_key, moderator_key], 2)
            if redeem_script != self.contract["buyer_order"]["order"][
                    "payment"]["redeem_script"]:
                raise Exception("Invalid redeem script")

            # verify the payment address
            if self.testnet:
                payment_address = bitcoin.p2sh_scriptaddr(redeem_script, 196)
            else:
                payment_address = bitcoin.p2sh_scriptaddr(redeem_script)
            if payment_address != self.contract["buyer_order"]["order"][
                    "payment"]["address"]:
                raise Exception("Incorrect payment address")

            return True

        except Exception:
            return False
Ejemplo n.º 15
0
    def add_purchase_info(
        self,
        quantity,
        ship_to=None,
        shipping_address=None,
        city=None,
        state=None,
        postal_code=None,
        country=None,
        moderator=None,
        options=None,
    ):
        """
        Update the contract with the buyer's purchase information.
        """

        profile = Profile(self.db).get()
        order_json = {
            "buyer_order": {
                "order": {
                    "ref_hash": digest(json.dumps(self.contract, indent=4)).encode("hex"),
                    "quantity": quantity,
                    "id": {
                        "guid": self.keychain.guid.encode("hex"),
                        "pubkeys": {
                            "guid": self.keychain.guid_signed_pubkey[64:].encode("hex"),
                            "bitcoin": bitcoin.bip32_extract_key(self.keychain.bitcoin_master_pubkey),
                            "encryption": self.keychain.encryption_pubkey.encode("hex"),
                        },
                    },
                    "payment": {},
                }
            }
        }
        if profile.HasField("handle"):
            order_json["buyer_order"]["order"]["id"]["blockchain_id"] = profile.handle
        if self.contract["vendor_offer"]["listing"]["metadata"]["category"] == "physical good":
            order_json["buyer_order"]["order"]["shipping"] = {}
            order_json["buyer_order"]["order"]["shipping"]["ship_to"] = ship_to
            order_json["buyer_order"]["order"]["shipping"]["address"] = shipping_address
            order_json["buyer_order"]["order"]["shipping"]["city"] = city
            order_json["buyer_order"]["order"]["shipping"]["state"] = state
            order_json["buyer_order"]["order"]["shipping"]["postal_code"] = postal_code
            order_json["buyer_order"]["order"]["shipping"]["country"] = country
        if options is not None:
            order_json["buyer_order"]["order"]["options"] = options
        if moderator:  # TODO: Handle direct payments
            chaincode = sha256(str(random.getrandbits(256))).digest().encode("hex")
            order_json["buyer_order"]["order"]["payment"]["chaincode"] = chaincode
            valid_mod = False
            for mod in self.contract["vendor_offer"]["listing"]["moderators"]:
                if mod["guid"] == moderator:
                    order_json["buyer_order"]["order"]["moderator"] = moderator
                    masterkey_m = mod["pubkeys"]["bitcoin"]["key"]
                    valid_mod = True
            if not valid_mod:
                return False
            masterkey_b = bitcoin.bip32_extract_key(self.keychain.bitcoin_master_pubkey)
            masterkey_v = self.contract["vendor_offer"]["listing"]["id"]["pubkeys"]["bitcoin"]
            buyer_key = derive_childkey(masterkey_b, chaincode)
            vendor_key = derive_childkey(masterkey_v, chaincode)
            moderator_key = derive_childkey(masterkey_m, chaincode)

            redeem_script = "75" + bitcoin.mk_multisig_script([buyer_key, vendor_key, moderator_key], 2)
            order_json["buyer_order"]["order"]["payment"]["redeem_script"] = redeem_script
            if self.testnet:
                payment_address = bitcoin.p2sh_scriptaddr(redeem_script, 196)
            else:
                payment_address = bitcoin.p2sh_scriptaddr(redeem_script)
            order_json["buyer_order"]["order"]["payment"]["address"] = payment_address

        price_json = self.contract["vendor_offer"]["listing"]["item"]["price_per_unit"]
        if "bitcoin" in price_json:
            order_json["buyer_order"]["order"]["payment"]["amount"] = price_json["bitcoin"]
        else:
            currency_code = price_json["fiat"]["currency_code"]
            fiat_price = price_json["fiat"]["price"]
            try:
                request = Request("https://api.bitcoinaverage.com/ticker/" + currency_code.upper() + "/last")
                response = urlopen(request)
                conversion_rate = response.read()
            except URLError:
                return False
            order_json["buyer_order"]["order"]["payment"]["amount"] = float(
                "{0:.8f}".format(float(fiat_price) / float(conversion_rate))
            )

        self.contract["buyer_order"] = order_json["buyer_order"]
        order = json.dumps(self.contract["buyer_order"]["order"], indent=4)
        self.contract["buyer_order"]["signature"] = self.keychain.signing_key.sign(
            order, encoder=nacl.encoding.HexEncoder
        )[:128]

        return self.contract["buyer_order"]["order"]["payment"]["address"]
Ejemplo n.º 16
0
def make_p2sh_address( script ):
    """
    Make a P2SH address
    """
    addr = bitcoin.p2sh_scriptaddr(script, multisig_version_byte)
    return addr
Ejemplo n.º 17
0
    def verify(self, sender_key):
        """
        Validate that an order sent over by a buyer is filled out correctly.
        """

        try:
            contract_dict = json.loads(json.dumps(self.contract, indent=4), object_pairs_hook=OrderedDict)
            del contract_dict["buyer_order"]
            contract_hash = digest(json.dumps(contract_dict, indent=4))

            ref_hash = unhexlify(self.contract["buyer_order"]["order"]["ref_hash"])

            # verify that the reference hash matches the contract and that the contract actually exists
            if contract_hash != ref_hash or not self.db.HashMap().get_file(ref_hash):
                raise Exception("Order for contract that doesn't exist")

            # verify the signature on the order
            verify_key = nacl.signing.VerifyKey(sender_key)
            verify_key.verify(
                json.dumps(self.contract["buyer_order"]["order"], indent=4),
                unhexlify(self.contract["buyer_order"]["signature"]),
            )

            # verify buyer included the correct bitcoin amount for payment
            price_json = self.contract["vendor_offer"]["listing"]["item"]["price_per_unit"]
            if "bitcoin" in price_json:
                asking_price = price_json["bitcoin"]
            else:
                currency_code = price_json["fiat"]["currency_code"]
                fiat_price = price_json["fiat"]["price"]
                request = Request("https://api.bitcoinaverage.com/ticker/" + currency_code.upper() + "/last")
                response = urlopen(request)
                conversion_rate = response.read()
                asking_price = float("{0:.8f}".format(float(fiat_price) / float(conversion_rate)))
            if asking_price > self.contract["buyer_order"]["order"]["payment"]["amount"]:
                raise Exception("Insuffient Payment")

            # verify a valid moderator was selected
            # TODO: handle direct payments
            valid_mod = False
            for mod in self.contract["vendor_offer"]["listing"]["moderators"]:
                if mod["guid"] == self.contract["buyer_order"]["order"]["moderator"]:
                    valid_mod = True
            if not valid_mod:
                raise Exception("Invalid moderator")

            # verify all the shipping fields exist
            if self.contract["vendor_offer"]["listing"]["metadata"]["category"] == "physical good":
                shipping = self.contract["buyer_order"]["order"]["shipping"]
                keys = ["ship_to", "address", "postal_code", "city", "state", "country"]
                for value in map(shipping.get, keys):
                    if value is None:
                        raise Exception("Missing shipping field")

            # verify buyer ID
            pubkeys = self.contract["buyer_order"]["order"]["id"]["pubkeys"]
            keys = ["guid", "bitcoin", "encryption"]
            for value in map(pubkeys.get, keys):
                if value is None:
                    raise Exception("Missing pubkey field")

            # verify redeem script
            chaincode = self.contract["buyer_order"]["order"]["payment"]["chaincode"]
            for mod in self.contract["vendor_offer"]["listing"]["moderators"]:
                if mod["guid"] == self.contract["buyer_order"]["order"]["moderator"]:
                    masterkey_m = mod["pubkeys"]["bitcoin"]["key"]

            masterkey_v = bitcoin.bip32_extract_key(self.keychain.bitcoin_master_pubkey)
            masterkey_b = self.contract["buyer_order"]["order"]["id"]["pubkeys"]["bitcoin"]
            buyer_key = derive_childkey(masterkey_b, chaincode)
            vendor_key = derive_childkey(masterkey_v, chaincode)
            moderator_key = derive_childkey(masterkey_m, chaincode)

            redeem_script = "75" + bitcoin.mk_multisig_script([buyer_key, vendor_key, moderator_key], 2)
            if redeem_script != self.contract["buyer_order"]["order"]["payment"]["redeem_script"]:
                raise Exception("Invalid redeem script")

            # verify the payment address
            if self.testnet:
                payment_address = bitcoin.p2sh_scriptaddr(redeem_script, 196)
            else:
                payment_address = bitcoin.p2sh_scriptaddr(redeem_script)
            if payment_address != self.contract["buyer_order"]["order"]["payment"]["address"]:
                raise Exception("Incorrect payment address")

            return True

        except Exception:
            return False