Beispiel #1
0
        public async Task <ActionResult> Action()
        {
            var  action = Request["Action"];
            var  args   = new Dictionary <string, string>();
            byte opcode = 0x01;

            var address = Request["Address"];

            var contractHash = new Address(address).Bytes;

            string key  = HttpServerUtility.UrlTokenEncode(contractHash);
            var    file = $"{key}";

            string contractCode = null;
            var    codeFile     = Path.ChangeExtension(Path.Combine("db", "contracts", file), ".txt");

            if (System.IO.File.Exists(codeFile))
            {
                contractCode = System.IO.File.ReadAllText(codeFile);
            }

            var contractInteraction = new ContractInteraction()
            {
                Action  = action,
                Address = new Address(contractHash, AddressType.Contract).ToString()
            };

            ContractMetadata contractMetadata = null;

            try
            {
                var _metadata = ContractExamples.Execution.metadata(contractCode);

                if (FSharpOption <ContractMetadata> .get_IsNone(_metadata))
                {
                    contractInteraction.Message = "No metadata";
                }
                else
                {
                    contractMetadata = _metadata.Value;
                }
            }
            catch
            {
                contractInteraction.Message = "Error getting metadata";
                return(View(contractInteraction));
            }

            if (contractMetadata.IsCallOption)
            {
                var callOptionParameters =
                    (ContractExamples.Execution.ContractMetadata.CallOption)contractMetadata;
                switch (action)
                {
                case "Collateralize":
                    //var pkAddress = new PKAddressField();
                    //pkAddress.SetValue(Request["return-address"]);

                    //if (pkAddress.Invalid)
                    //{
                    //             contractInteraction.Message = "Invalid return address";
                    //	return View(contractInteraction);
                    //}

                    //args.Add("returnPubKeyAddress", pkAddress.Value);
                    opcode = OPCODE_COLLATERALIZE;
                    break;

                case "Exercise":
                    var pkExerciseReturnAddress = new PKAddressField();
                    pkExerciseReturnAddress.SetValue(Request["exercise-return-address"]);

                    if (pkExerciseReturnAddress.Invalid)
                    {
                        contractInteraction.Message = "Invalid send address";
                        return(View(contractInteraction));
                    }

                    args.Add("returnPubKeyAddress", pkExerciseReturnAddress.Value);

                    string oracleData;     //GetOracleCommitmentData(callOptionParameters.Item.underlying, DateTime.Now.ToUniversalTime()).Result;

                    if (GetLastData(callOptionParameters.Item.underlying, out oracleData))
                    {
                        args.Add("oracleRawData", oracleData);
                    }
                    else
                    {
                        contractInteraction.Message = "Error getting oracle data";
                        return(View(contractInteraction));
                    }

                    opcode = OPCODE_EXERCISE;
                    break;

                case "Buy":
                    var pkSendAddress = new PKAddressField();
                    pkSendAddress.SetValue(Request["buy-send-address"]);

                    if (pkSendAddress.Invalid)
                    {
                        contractInteraction.Message = "Invalid send address";
                        return(View(contractInteraction));
                    }

                    args.Add("returnPubKeyAddress", pkSendAddress.Value);
                    opcode = OPCODE_BUY;
                    break;
                    //case "Close":
                    //	opcode = OPCODE_CLOSE;
                    //	break;
                }
            }

            var argsMap = new FSharpMap <string, string>(args.Select(t => new Tuple <string, string>(t.Key, t.Value)));
            var result  = await Client.Send <GetContractPointedOutputsResultPayload>(_address, new GetContractPointedOutputsPayload()
            {
                ContractHash = contractHash
            });

            var utxos = GetContractPointedOutputsResultPayload.Unpack(result.PointedOutputs);
            var data  = ContractUtilities.DataGenerator.makeJson(contractMetadata, utxos, opcode, argsMap);

            if (data.IsError)
            {
                contractInteraction.Message = data.ErrorValue.ToString();
            }
            else
            {
                contractInteraction.Data = data.ResultValue.JsonValue.ToString();
            }

            return(View(contractInteraction));
        }
Beispiel #2
0
        public ActionResult Generate()
        {
            if (!Directory.Exists("db"))
            {
                Directory.CreateDirectory("db");
            }

            var contractManager = new OracleContractManager();

            if (!contractManager.IsSetup)
            {
                ViewData["Result"]  = false;
                ViewData["Message"] = contractManager.Message;
                return(View());
            }

            _StockAPI.Tickers = WebConfigurationManager.AppSettings["tickers"].Split(',');

            var rawTickers     = _StockAPI.FetchResults().Result;
            var now            = DateTime.Now.ToUniversalTime();
            var nowTicks       = now.Ticks;
            var items          = rawTickers.Select(t => new ContractExamples.Oracle.TickerItem(t.Name, t.Value, nowTicks));
            var secret         = Convert.FromBase64String(WebConfigurationManager.AppSettings["oracleSecret"]);
            var commitmentData = ContractExamples.Oracle.commitments(items, secret);

            var getOutpointsResult = Client.Send <GetContractPointedOutputsResultPayload>(NodeRPCAddress, new GetContractPointedOutputsPayload()
            {
                ContractHash = contractManager.ContractAddress.Bytes
            }).Result;

            if (!getOutpointsResult.Success || getOutpointsResult.PointedOutputs.Count == 0)
            {
                ViewData["Result"]  = false;
                ViewData["Message"] = "Could not find outputs";
                return(View());
            }

            var utxos = GetContractPointedOutputsResultPayload.Unpack(getOutpointsResult.PointedOutputs);

            if (utxos.Count() == 0)
            {
                ViewData["Result"]  = false;
                ViewData["Message"] = "Could not find output";
                return(View());
            }

            var utxo = utxos.First();


            //var serializer = new ContractExamples.FStarCompatibility.DataSerializer(Consensus.Serialization.context);
            //Consensus.Serialization.context.Serializers.RegisterOverride(serializer);

            var data = ContractUtilities.DataGenerator.makeOracleMessage(commitmentData.Item2, utxo.Item1);
            //var data = ContractExamples.QuotedContracts.simplePackOutpoint(utxo.Item1)
            //			   .Concat(commitmentData.Item2).ToArray();

            //var signiture = Authentication.sign(data, contractManager.PrivateKey);

            //data = data.Concat(signiture).ToArray();

            var sendContractResult = Client.Send <SendContractResultPayload>(NodeRPCAddress, new SendContractPayload()
            {
                ContractHash = contractManager.ContractAddress.Bytes,
                Data         = data
            }).Result;

            ViewData["Result"] = sendContractResult.Success;

            if (sendContractResult.Success)
            {
                var          file = Path.Combine("db", $"{now.ToFileTime()}");
                MemoryStream ms   = new MemoryStream();
                ContractExamples.Oracle.proofMapSerializer.WriteObject(ms, commitmentData.Item1);
                ms.Position = 0;
                var sr = new StreamReader(ms);
                System.IO.File.WriteAllText(Path.ChangeExtension(file, ".data.json"), sr.ReadToEnd());

                var outpoint = new Types.Outpoint(sendContractResult.TxHash, 1);                 // oracle always puts data on output #1

                System.IO.File.WriteAllText(Path.ChangeExtension(file, ".outpoint.txt"), Convert.ToBase64String(Merkle.serialize(outpoint)));
            }
            else
            {
                ViewData["Message"] = "Reason: send result was '" + sendContractResult.Message + "'";
            }

            return(View());
        }
Beispiel #3
0
        public async Task <ActionResult> Index(string id)
        {
            var contractData = new App_Data.ContractData()
            {
                ActiveContract = new ActiveContract()
            };

            Directory.CreateDirectory(Path.Combine("db", "contracts"));
            Directory.CreateDirectory(Path.Combine("db", "asset-metadata"));

            var contractHash = HttpServerUtility.UrlTokenDecode(id);
            var file         = $"{id}";

            string contractCode = null;
            var    codeFile     = Path.ChangeExtension(Path.Combine("db", "contracts", file), ".txt");

            if (System.IO.File.Exists(codeFile))
            {
                contractCode = System.IO.File.ReadAllText(codeFile);
                contractData.ActiveContract.Code = contractCode;
            }

            var assetMetaDataFile = Path.ChangeExtension(Path.Combine("db", "asset-metadata", file), ".json");

            if (System.IO.File.Exists(assetMetaDataFile))
            {
                try
                {
                    var json          = System.IO.File.ReadAllText(assetMetaDataFile);
                    var assetMetaData = JsonConvert.DeserializeObject <AssetMetadata>(json);

                    contractData.ActiveContract.AssetName            = assetMetaData.name;
                    contractData.ActiveContract.AssetImageUrl        = assetMetaData.imageUrl;
                    contractData.ActiveContract.AssetMetadataVersion = assetMetaData.version;
                } catch
                {
                    contractData.ActiveContract.AssetName = "Bad metadata";
                }
            }

            var result = await Client.Send <GetContractPointedOutputsResultPayload>(_address, new GetContractPointedOutputsPayload()
            {
                ContractHash = contractHash
            });

            contractData.ActiveContract.TotalAssets = result.Success ? (ulong)result.PointedOutputs.Count : 0UL;
            //var contractTotalAssetsResult = await Client.Send<GetContractTotalAssetsResultPayload>(address, new GetContractTotalAssetsPayload()
            //{
            //	Hash = new Wallet.core.Data.Address(Convert.ToBase64String(contractHash)).Bytes
            //});
            contractData.ActiveContract.Address = new Wallet.core.Data.Address(contractHash, Wallet.core.Data.AddressType.Contract).ToString();

            if (contractCode != null)
            {
                contractData.ActiveContract.Code = contractCode;
                Utils.SetContractInfo(contractData.ActiveContract, contractCode);

                var utxos = GetContractPointedOutputsResultPayload.Unpack(result.PointedOutputs);

                var stateOutputOption  = ContractUtilities.DataGenerator.getCallOptionDataPOutput(contractData.ActiveContract.Numeraire, utxos);
                var isSomeOutputOption = FSharpOption <Tuple <Consensus.Types.Outpoint, Consensus.Types.Output> > .get_IsSome(stateOutputOption);

                contractData.ActiveContract.Initialized = isSomeOutputOption;
            }

            //string oracleService = WebConfigurationManager.AppSettings["oracleService"];
            contractData.ActiveContract.OracleTickerUrl = $"/OracleData/ShowTicker?ticker={contractData.ActiveContract.Underlying}";

            return(View(contractData));
        }
Beispiel #4
0
        async Task <ResultPayload> GetResult(BasePayload payload)
        {
            var type = payload.Type;

            if (type == typeof(SpendPayload))
            {
                var spendPayload = (SpendPayload)payload;

                var _result = await _App.Spend(new Address(spendPayload.Address), spendPayload.Amount);

                return(new ResultPayload {
                    Success = _result
                });
            }

            if (type == typeof(SendContractPayload))
            {
                var sendContractPayload = (SendContractPayload)payload;

                var result = await new ExecuteContractAction()
                {
                    ContractHash = sendContractPayload.ContractHash,
                    Message      = sendContractPayload.Data
                }.Publish();

                if (!result.Item1)
                {
                    return(new SendContractResultPayload {
                        Success = false
                    });
                }

                var transmitResult = await _App.NodeManager.Transmit(result.Item2);

                if (transmitResult != BlockChain.BlockChain.TxResultEnum.Accepted)
                {
                    return(new SendContractResultPayload {
                        Success = false, Message = transmitResult.ToString()
                    });
                }

                return(new SendContractResultPayload {
                    Success = true, TxHash = Consensus.Merkle.transactionHasher.Invoke(result.Item2)
                });
            }

            if (type == typeof(ActivateContractPayload))
            {
                var activateContractPayload = (ActivateContractPayload)payload;

                var amount = (ulong)BlockChain.ActiveContractSet.KalapasPerBlock(activateContractPayload.Code) * (ulong)activateContractPayload.Blocks;

                Consensus.Types.Transaction tx;
                var success = _App.WalletManager.GetContractActivationTx(Encoding.ASCII.GetBytes(activateContractPayload.Code), amount, out tx);

                var resultPayload = new ResultPayload();

                if (!success)
                {
                    resultPayload.Message = "Could not get signed tx";
                    resultPayload.Success = false;
                }
                else
                {
                    var transmitResult = await _App.NodeManager.Transmit(tx);

                    if (transmitResult != BlockChain.BlockChain.TxResultEnum.Accepted)
                    {
                        resultPayload.Message = "Could not transmit. Result: " + transmitResult;
                        resultPayload.Success = false;
                    }
                    else
                    {
                        resultPayload.Success = true;
                    }
                }

                return(resultPayload);
            }

            if (type == typeof(GetACSPayload))
            {
                return(new GetACSResultPayload()
                {
                    Success = true,
                    Contracts = new GetActiveContractsAction().Publish().Result.Select(t => new ContractData()
                    {
                        Hash = t.Hash,
                        LastBlock = t.LastBlock,
                        Code = new GetContractCodeAction(t.Hash).Publish().Result
                    }).ToArray()
                });
            }

            if (type == typeof(HelloPayload))
            {
                return(new HelloResultPayload());
            }

            //if (type == typeof(GetContractCodePayload))
            //{
            //  var contractHash = ((GetContractCodePayload)payload).Hash;
            //             return new GetContractCodeResultPayload() { Success = true, Code = _App.GetContractCode(contractHash) };
            //}

            if (type == typeof(GetContractTotalAssetsPayload))
            {
                var contractHash = ((GetContractTotalAssetsPayload)payload).Hash;
                //  var totals = _App.GetTotalAssets(contractHash);
                return(new GetContractTotalAssetsResultPayload
                {
                    Confirmed = 999,                     // totals.Item1,
                    Unconfirmed = 999                    // totals.Item2
                });
            }

            if (type == typeof(GetContractPointedOutputsPayload))
            {
                var _payload = (GetContractPointedOutputsPayload)payload;
                var result   = new GetContractPointedOutputsAction(_payload.ContractHash).Publish().Result;

                return(new GetContractPointedOutputsResultPayload
                {
                    Success = true,
                    PointedOutputs = GetContractPointedOutputsResultPayload.Pack(result)
                });
            }

            if (type == typeof(MakeTransactionPayload))
            {
                var _payload = (MakeTransactionPayload)payload;
                var result   = await _App.Spend(new Address(_payload.Address), _payload.Amount);

                return(new ResultPayload
                {
                    Success = result
                });
            }

            if (type == typeof(EnsureTestKeyAcquiredPayload))
            {
                var privateKey = ((EnsureTestKeyAcquiredPayload)payload).PrivateKey;

                if (!_App.TestKeyImported(privateKey))
                {
                    _App.WalletManager.Import(Key.Create(privateKey));
                }

                return(new ResultPayload
                {
                    Success = _App.TestKeyImported(privateKey)
                });
            }

            //if (type == typeof(GetBalancePayload))
            //{
            //  var _payload = (GetBalancePayload)payload;

            //  return new GetBalanceResultPayload
            //  {
            //      Success = true,
            //                 Balance = _App.CalcBalance(_payload.Asset)
            //  };
            //}

            return(null);
        }