예제 #1
0
    def StandbyValidators():
        if len(Blockchain._validators) < 1:
            vlist = settings.STANDBY_VALIDATORS
            for pkey in settings.STANDBY_VALIDATORS:
                Blockchain._validators.append(ECDSA.decode_secp256r1(pkey).G)

        return Blockchain._validators
예제 #2
0
    def Deserialize(self, reader):
        """
        Deserialize full object.

        Args:
            reader (neo.Core.IO.BinaryReader):
        """
        super(AssetState, self).Deserialize(reader)
        self.AssetId = reader.ReadUInt256()
        self.AssetType = ord(reader.ReadByte())
        self.Name = reader.ReadVarString()

        position = reader.stream.tell()

        try:
            self.Amount = reader.ReadFixed8()
        except Exception:
            reader.stream.seek(position)
            self.Amount = reader.ReadFixed8()

        self.Available = reader.ReadFixed8()
        self.Precision = ord(reader.ReadByte())

        # fee mode
        reader.ReadByte()

        self.Fee = reader.ReadFixed8()
        self.FeeAddress = reader.ReadUInt160()
        self.Owner = ECDSA.Deserialize_Secp256r1(reader)
        self.Admin = reader.ReadUInt160()
        self.Issuer = reader.ReadUInt160()
        self.Expiration = reader.ReadUInt32()
        self.IsFrozen = reader.ReadBool()
예제 #3
0
def gather_param(index, param_type, do_continue=True):
    ptype = ContractParameterType(param_type)
    prompt_message = '[Param %s] %s input: ' % (index, ptype.name)

    try:
        result = get_input_prompt(prompt_message)
    except KeyboardInterrupt:
        print("Input cancelled")
        return None, True
    except Exception as e:
        print(str(e))
        # no results, abort True
        return None, True

    try:

        if ptype == ContractParameterType.String:
            return str(result), False
        elif ptype == ContractParameterType.Integer:
            return int(result), False
        elif ptype == ContractParameterType.Boolean:
            return bool(result), False
        elif ptype == ContractParameterType.PublicKey:
            try:
                return ECDSA.decode_secp256r1(result).G, False
            except ValueError:
                return None, True
        elif ptype == ContractParameterType.ByteArray:
            if isinstance(result,
                          str) and len(result) == 34 and result[0] == 'A':
                return Helper.AddrStrToScriptHash(result).Data, False
            res = eval(
                result,
                {"__builtins__": {
                    'bytearray': bytearray,
                    'bytes': bytes
                }}, {})
            if isinstance(res, bytes):
                return bytearray(res), False
            return res, False

        elif ptype == ContractParameterType.Array:
            res = eval(result)
            if isinstance(res, list):
                return res, False
            raise Exception("Please provide a list")
        else:
            raise Exception("Unknown param type %s " % ptype.name)

    except KeyboardInterrupt:  # Control-C pressed: exit

        return None, True

    except Exception as e:

        print("Could not parse param as %s : %s " % (ptype, e))
        if do_continue:
            return gather_param(index, param_type, do_continue)

    return None, True
예제 #4
0
    def Deserialize(self, reader: BinaryReader):
        """
        Deserialize full object.

        Args:
            reader (neo.Core.IO.BinaryReader):
        """
        super(ValidatorState, self).Deserialize(reader)
        self.PublicKey = ECDSA.Deserialize_Secp256r1(reader)
        self.Registered = reader.ReadBool()
        self.Votes = reader.ReadFixed8()
예제 #5
0
    def DeserializeExclusiveData(self, reader):
        """
        Deserialize full object.

        Args:
            reader (neo.IO.BinaryReader):

        Raises:
            Exception: If the version read is incorrect.
        """
        if self.Version is not 0:
            raise Exception('Invalid format')

        self.PublicKey = ECDSA.Deserialize_Secp256r1(reader)
예제 #6
0
    def __init__(self, priv_key):
        """
        Create an instance.

        Args:
            priv_key (bytes): a private key.

        Raises:
            ValueError:
                if the input `priv_key` length is not 32, 96, or 104
                if the input `priv_key` length is 32 but the public key still could not be determined
        """
        self.setup_curve()
        self.PublicKeyHash = None
        self.PublicKey = None
        self.PrivateKey = None

        length = len(priv_key)

        if length != 32 and length != 96 and length != 104:
            raise ValueError("Invalid private key")

        self.PrivateKey = bytearray(priv_key[-32:])

        pubkey_encoded_not_compressed = None

        if length == 32:
            try:
                pubkey_encoded_not_compressed = bitcoin.privkey_to_pubkey(
                    priv_key)
            except Exception:
                raise ValueError("Could not determine public key")

        elif length == 96 or length == 104:
            skip = length - 96
            pubkey_encoded_not_compressed = bytearray(b'\x04') + bytearray(
                priv_key[skip:skip + 64])

        if pubkey_encoded_not_compressed:
            pubkey_points = bitcoin.decode_pubkey(
                pubkey_encoded_not_compressed, 'bin')

            pubx = pubkey_points[0]
            puby = pubkey_points[1]
            edcsa = ECDSA.secp256r1()
            self.PublicKey = edcsa.Curve.point(pubx, puby)

        self.PublicKeyHash = Crypto.ToScriptHash(
            self.PublicKey.encode_point(True), unhex=True)
예제 #7
0
    def DeserializeExclusiveData(self, reader):
        """
        Deserialize full object.

        Args:
            reader (neo.IO.BinaryReader):
        """
        self.Type = TransactionType.RegisterTransaction
        self.AssetType = ord(reader.ReadByte())
        self.Name = reader.ReadVarString()
        self.Amount = reader.ReadFixed8()
        self.Precision = ord(reader.ReadByte())
        self.Owner = ECDSA.Deserialize_Secp256r1(reader)
        #        self.Owner = ecdsa.G
        self.Admin = reader.ReadUInt160()
예제 #8
0
    def SystemShare():
        """
        Register AntShare.

        Returns:
            RegisterTransaction:
        """
        amount = Fixed8.FromDecimal(
            sum(Blockchain.GENERATION_AMOUNT) * Blockchain.DECREMENT_INTERVAL)
        owner = ECDSA.secp256r1().Curve.Infinity
        admin = Crypto.ToScriptHash(PUSHT)
        return RegisterTransaction(
            [], [], AssetType.GoverningToken,
            "[{\"lang\":\"zh-CN\",\"name\":\"小蚁股\"},{\"lang\":\"en\",\"name\":\"AntShare\"}]",
            amount, 0, owner, admin)
예제 #9
0
def gather_signatures(context, itx, owners):
    do_exit = False
    print("\n\n*******************\n")
    print("Gather Signatures for Transaction:\n%s " %
          json.dumps(itx.ToJson(), indent=4))
    print("Please use a client to sign the following: %s " % itx.GetHashData())

    owner_index = 0
    while not context.Completed and not do_exit:

        next_script = owners[owner_index]
        next_addr = scripthash_to_address(next_script.Data)
        try:
            print("\n*******************\n")
            owner_input = prompt('Public Key and Signature for %s> ' %
                                 next_addr)
            items = owner_input.split(' ')
            pubkey = ECDSA.decode_secp256r1(items[0]).G
            sig = items[1]
            contract = Contract.CreateSignatureContract(pubkey)

            if contract.Address == next_addr:
                context.Add(contract, 0, sig)
                print("Adding signature %s " % sig)
                owner_index += 1
            else:
                print("Public Key does not match address %s " % next_addr)

        except ValueError:
            # expected from ECDSA if public key is invalid
            print(f"Invalid public key: {items[0]}")
            do_exit = True
        except EOFError:
            # Control-D pressed: quit
            do_exit = True
        except KeyboardInterrupt:
            # Control-C pressed: do nothing
            do_exit = True
        except Exception as e:
            print("Could not parse input %s " % e)

    if context.Completed:
        print("Signatures complete")
        itx.scripts = context.GetScripts()
        return True
    else:
        print("Could not finish signatures")
        return False
예제 #10
0
    def FromJson(json):
        """
        Convert a json object to a ContractParameter object

        Args:
            item (dict): The item to convert to a ContractParameter object

        Returns:
            ContractParameter

        """
        type = ContractParameterType.FromString(json['type'])

        value = json['value']
        param = ContractParameter(type=type, value=None)

        if type == ContractParameterType.Signature or type == ContractParameterType.ByteArray:
            param.Value = bytearray.fromhex(value)

        elif type == ContractParameterType.Boolean:
            param.Value = bool(value)

        elif type == ContractParameterType.Integer:
            param.Value = int(value)

        elif type == ContractParameterType.Hash160:
            param.Value = UInt160.ParseString(value)

        elif type == ContractParameterType.Hash256:
            param.Value = UInt256.ParseString(value)

        # @TODO Not sure if this is working...
        elif type == ContractParameterType.PublicKey:
            param.Value = ECDSA.decode_secp256r1(value).G

        elif type == ContractParameterType.String:
            param.Value = str(value)

        elif type == ContractParameterType.Array:
            val = [ContractParameter.FromJson(item) for item in value]
            param.Value = val

        return param
예제 #11
0
    def SystemCoin():
        """
        Register AntCoin

        Returns:
            RegisterTransaction:
        """
        amount = Fixed8.FromDecimal(
            sum(Blockchain.GENERATION_AMOUNT) * Blockchain.DECREMENT_INTERVAL)

        owner = ECDSA.secp256r1().Curve.Infinity

        precision = 8
        admin = Crypto.ToScriptHash(PUSHF)

        return RegisterTransaction(
            [], [], AssetType.UtilityToken,
            "[{\"lang\":\"zh-CN\",\"name\":\"小蚁币\"},{\"lang\":\"en\",\"name\":\"AntCoin\"}]",
            amount, precision, owner, admin)
예제 #12
0
    def Runtime_CheckWitness(self, engine: ExecutionEngine):
        hashOrPubkey = engine.CurrentContext.EvaluationStack.Pop().GetByteArray()

        result = False

        if len(hashOrPubkey) == 20:
            result = self.CheckWitnessHash(engine, UInt160(data=hashOrPubkey))

        elif len(hashOrPubkey) == 33:
            try:
                point = ECDSA.decode_secp256r1(hashOrPubkey, unhex=False).G
            except ValueError:
                return False
            result = self.CheckWitnessPubkey(engine, point)
        else:
            return False

        engine.CurrentContext.EvaluationStack.PushT(result)

        return True
예제 #13
0
    def CreateMultiSigContract(publicKeyHash, m, publicKeys):

        pk = [ECDSA.decode_secp256r1(p).G for p in publicKeys]
        return Contract(Contract.CreateMultiSigRedeemScript(m, pk),
                        bytearray(m), publicKeyHash)
예제 #14
0
    def AddSignature(self, contract, pubkey, signature):

        if contract.Type == ContractType.MultiSigContract:

            item = self.CreateItem(contract)
            if item is None:
                return False
            for p in item.ContractParameters:
                if p.Value is not None:
                    return False
            if item.Signatures is None:
                item.Signatures = {}
            elif pubkey.encode_point(True) in item.Signatures:
                return False

            ecdsa = ECDSA.secp256r1()
            points = []
            temp = binascii.unhexlify(contract.Script)
            ms = MemoryStream(binascii.unhexlify(contract.Script))
            reader = BinaryReader(ms)
            numr = reader.ReadUInt8()
            try:
                while reader.ReadUInt8() == 33:
                    ecpoint = ecdsa.ec.decode_from_hex(
                        binascii.hexlify(reader.ReadBytes(33)).decode())
                    points.append(ecpoint)
            except ValueError:
                return False
            finally:
                ms.close()

            if pubkey not in points:
                return False

            item.Signatures[pubkey.encode_point(
                True).decode()] = binascii.hexlify(signature)

            if len(item.Signatures) == len(contract.ParameterList):

                i = 0
                points.sort(reverse=True)
                for k in points:
                    pubkey = k.encode_point(True).decode()
                    if pubkey in item.Signatures:
                        if self.Add(contract, i,
                                    item.Signatures[pubkey]) is None:
                            raise Exception("Invalid operation")
                        i += 1
                item.Signatures = None
            return True

        else:
            index = -1
            if contract.ParameterList == '00':
                contract.ParameterList = b'\x00'
            length = len(contract.ParameterList)
            for i in range(0, length):
                if ContractParameterType(contract.ParameterList[i]
                                         ) == ContractParameterType.Signature:
                    if index >= 0:
                        raise Exception("Signature must be first")
                    else:
                        index = i
            return self.Add(contract, index, signature)
예제 #15
0
    def Asset_Create(self, engine: ExecutionEngine):

        tx = engine.ScriptContainer

        asset_type = int(
            engine.CurrentContext.EvaluationStack.Pop().GetBigInteger())

        if asset_type not in AssetType.AllTypes() or \
                asset_type == AssetType.CreditFlag or \
                asset_type == AssetType.DutyFlag or \
                asset_type == AssetType.GoverningToken or \
                asset_type == AssetType.UtilityToken:
            return False

        if len(engine.CurrentContext.EvaluationStack.Peek().GetByteArray()
               ) > 1024:
            return False

        name = engine.CurrentContext.EvaluationStack.Pop().GetByteArray(
        ).decode('utf-8')

        amount = Fixed8(
            engine.CurrentContext.EvaluationStack.Pop().GetBigInteger())

        if amount == Fixed8.Zero() or amount < Fixed8.NegativeSatoshi():
            return False

        if asset_type == AssetType.Invoice and amount != Fixed8.NegativeSatoshi(
        ):
            return False

        precision = int(
            engine.CurrentContext.EvaluationStack.Pop().GetBigInteger())

        if precision > 8:
            return False

        if asset_type == AssetType.Share and precision != 0:
            return False

        if amount != Fixed8.NegativeSatoshi() and amount.value % pow(
                10, 8 - precision) != 0:
            return False

        ownerData = engine.CurrentContext.EvaluationStack.Pop().GetByteArray()

        try:
            owner = ECDSA.decode_secp256r1(ownerData, unhex=False).G
        except ValueError:
            return False

        if owner.IsInfinity:
            return False

        if not self.CheckWitnessPubkey(engine, owner):
            logger.error("check witness false...")
            return False

        admin = UInt160(
            data=engine.CurrentContext.EvaluationStack.Pop().GetByteArray())

        issuer = UInt160(
            data=engine.CurrentContext.EvaluationStack.Pop().GetByteArray())

        new_asset = AssetState(asset_id=tx.Hash,
                               asset_type=asset_type,
                               name=name,
                               amount=amount,
                               available=Fixed8.Zero(),
                               precision=precision,
                               fee_mode=0,
                               fee=Fixed8.Zero(),
                               fee_addr=UInt160(),
                               owner=owner,
                               admin=admin,
                               issuer=issuer,
                               expiration=Blockchain.Default().Height + 1 +
                               2000000,
                               is_frozen=False)

        asset = self._assets.ReplaceOrAdd(tx.Hash.ToBytes(), new_asset)

        # print("*****************************************************")
        # print("CREATED ASSET %s " % tx.Hash.ToBytes())
        # print("*****************************************************")
        engine.CurrentContext.EvaluationStack.PushT(
            StackItem.FromInterface(asset))

        return True