Esempio n. 1
0
    public void ShowOracleInfo()
    {
        oracleTitleImage.sprite = oracleTitleSprites[Localisation.currentLanguage];

        foreach (Transform child in pageParent.transform)
        {
            Destroy(child.gameObject);
        }

        // destroy childs of paginationParent
        foreach (Transform child in paginationParent.transform)
        {
            Destroy(child.gameObject);
        }



        List <OracleData> oracleDataLog = OracleManager.Instance.OracleDataLog;

        foreach (OracleData oracleData in oracleDataLog)
        {
            OracleInfo info = Instantiate(oracleInfoPrefab);
            GameObject pag  = Instantiate(paginationPrefab);

            pag.transform.SetParent(paginationParent, false);
            info.transform.SetParent(pageParent, false);

            scrollSnap.AddToBack(info.gameObject);

            var item = ItemManager.instance.itemsData.GetItemByName(oracleData.itemName);
            info.InitUI(item.sprite, oracleData.bestPriceIndex);
        }
    }
Esempio n. 2
0
        public void FullExchange2()
        {
            var initiatorInputKey = new Key();
            var acceptorInputKey  = new Key();

            var offerKey  = new Key();
            var acceptKey = new Key();

            var initiator = new DLCTransactionBuilder(true, null, null, null, Network.RegTest);
            var acceptor  = new DLCTransactionBuilder(false, null, null, null, Network.RegTest);

            var oracleInfo         = OracleInfo.Parse("e4d36e995ff4bba4da2b60ad907d61d36e120d6f7314a3c2a20c6e27a5cd850ff67f8f41718c86f05eb95fab308f5ed788a2a963124299154648f97124caa579");
            var requiredCollateral = initiator.Offer(oracleInfo.PubKey, oracleInfo.RValue,
                                                     new DiscretePayoffs()
            {
                new DiscretePayoff("Republicans", Money.Coins(0.4m)),
                new DiscretePayoff("Democrats", -Money.Coins(0.6m)),
                new DiscretePayoff("Smith", Money.Zero)
            }, new Timeouts()
            {
                ContractMaturity = 100,
                ContractTimeout  = 200
            });
            var fund1 = GetFundingPSBT(acceptorInputKey, requiredCollateral);
            var offer = initiator.FundOffer(offerKey, fund1);

            var payoff = acceptor.Accept(offer);
            var fund2  = GetFundingPSBT(initiatorInputKey, payoff.CalculateMinimumCollateral());
            var accept = acceptor.FundAccept(acceptKey, fund2);

            initiator.Sign1(accept);
            var fundPSBT = initiator.GetFundingPSBT();

            fundPSBT.SignWithKeys(initiatorInputKey);
            var sign = initiator.Sign2(offerKey, fundPSBT);

            acceptor.Finalize1(sign);
            fundPSBT = acceptor.GetFundingPSBT();
            fundPSBT.SignWithKeys(acceptorInputKey);
            var fullyVerified = acceptor.Finalize(fundPSBT);

            foreach (var i in fullyVerified.Inputs)
            {
                Assert.NotNull(i.WitScript);
            }

            var cet          = initiator.BuildCET(offer.ContractInfo[0].Outcome);
            var keyBytes     = Encoders.Hex.DecodeData("d1da46f96f0be50bce2bbabe6bc8633f448ec3f1d14715a0b086b68ed34e095d");
            var oracleSecret = new Key(keyBytes);

            var sig = oracleInfo.RValue.CreateSchnorrSignature(oracleSecret.ToECPrivKey());

            Assert.True(oracleInfo.PubKey.SigVerifyBIP340(sig, new DiscreteOutcome("Republicans").Hash));

            initiator.BuildSignedCET(offerKey, oracleSecret);

            this.testOutputHelper.WriteLine("----Final state------");
            testOutputHelper.WriteLine(JObject.Parse(initiator.ExportState()).ToString(Formatting.Indented));
            this.testOutputHelper.WriteLine("---------------------");
        }
Esempio n. 3
0
        private void executeDbMethodWithSpecifiedDatabaseInfo(OracleInfo info, Action <DBConnection> method)
        {
            executeMethodWithDbExceptionHandling(
                () => {
                var connection = new DBConnection(new OracleInfo(info.ConnectionString, info.SupportsLinguisticIndexes));

                connection.ExecuteWithConnectionOpen(() => method(connection));
            });
        }
Esempio n. 4
0
        private string GetEventFilePath(OracleInfo eventFullId)
        {
            var output = new byte[64];

            eventFullId.WriteToBytes(output);
            var hash = Hashes.SHA256(output);
            var dir  = Path.Combine(RepositoryDirectory, "Events");

            return(Path.Combine(dir, Encoders.Base58.EncodeData(hash)) + ".json");
        }
Esempio n. 5
0
        public void CheckAttestationMatchBitcoinS()
        {
            var oracleInfo = OracleInfo.Parse("156c7d1c7922f0aa1168d9e21ac77ea88bbbe05e24e70a08bbe0519778f2e5daea3a68d8749b81682513b0479418d289d17e24d4820df2ce979f1a56a63ca525");

            Assert.True(oracleInfo.TryComputeSigpoint(new DiscreteOutcome("Democrat_win"), out var sigpoint));
            var attestation = Context.Instance.CreateECPrivKey(Encoders.Hex.DecodeData("77a5aabd716936411bbe19219bd0b261fae8f0524367268feb264e0a3b215766"));
            var pubKey      = attestation.CreatePubKey();

            Assert.Equal(sigpoint, pubKey);
        }
Esempio n. 6
0
        public void FullExchange2()
        {
            var initiatorInputKey = new Key();
            var acceptorInputKey  = new Key();

            var fund1     = GetFundingPSBT(initiatorInputKey, Money.Coins(0.6m));
            var fund2     = GetFundingPSBT(acceptorInputKey, Money.Coins(0.4m));
            var initiator = new DLCTransactionBuilder(true, null, null, null, Network.RegTest);
            var acceptor  = new DLCTransactionBuilder(false, null, null, null, Network.RegTest);

            var oracleInfo = OracleInfo.Parse("156c7d1c7922f0aa1168d9e21ac77ea88bbbe05e24e70a08bbe0519778f2e5daea3a68d8749b81682513b0479418d289d17e24d4820df2ce979f1a56a63ca525");
            var offer      = initiator.Offer(PSBTFundingTemplate.Parse(fund1), oracleInfo,
                                             ContractInfo.CreateContract(
                                                 ("Republicans_win", Money.Coins(1.0m)),
                                                 ("Democrats_win", Money.Coins(0m)),
                                                 ("other", Money.Coins(0.6m))), new Timeouts()
            {
                ContractMaturity = 100,
                ContractTimeout  = 200
            });
            var accept = acceptor.Accept(offer, PSBTFundingTemplate.Parse(fund2));

            initiator.VerifySign(accept);
            var fundPSBT = initiator.BuildFundingPSBT();

            fundPSBT.SignWithKeys(initiatorInputKey);
            var sign = initiator.EndSign(fundPSBT);

            acceptor.VerifySign(sign);
            fundPSBT = acceptor.BuildFundingPSBT();
            fundPSBT.SignWithKeys(acceptorInputKey);
            var psbt = acceptor.CombineFunding(fundPSBT);

            psbt = psbt.Finalize();
            var fullyVerified = psbt.ExtractTransaction();

            foreach (var i in fullyVerified.Inputs)
            {
                Assert.NotNull(i.WitScript);
            }

            var cet      = initiator.BuildCET(offer.ContractInfo[0].Outcome);
            var keyBytes = Encoders.Hex.DecodeData("39eabd151030f4f2d518fb8a8d00f679aa9e034c66263032a1245a04cfbc592b");
            //Array.Reverse(keyBytes);
            var oracleSecret = new Key(keyBytes);

            initiator.BuildSignedCET(oracleSecret);
        }
Esempio n. 7
0
        private void executeDbMethodWithSpecifiedDatabaseInfo(OracleInfo info, Action <DBConnection> method)
        {
            executeMethodWithDbExceptionHandling(
                delegate {
                // Before we disabled pooling, we couldn't repeatedly perform Update Data operations since users with open connections can't be dropped.
                var connection = new DBConnection(
                    new OracleInfo(
                        (info as DatabaseInfo).SecondaryDatabaseName,
                        info.DataSource,
                        info.UserAndSchema,
                        info.Password,
                        false,
                        info.SupportsLinguisticIndexes));

                connection.ExecuteWithConnectionOpen(() => method(connection));
            });
        }
Esempio n. 8
0
        public async Task <Event?> GetEvent(OracleInfo eventFullId)
        {
            var dir = Path.Combine(RepositoryDirectory, "Events");

            if (!Directory.Exists(dir))
            {
                return(null);
            }

            var eventFilePath = GetEventFilePath(eventFullId);

            if (!File.Exists(eventFilePath))
            {
                return(null);
            }
            return(JsonConvert.DeserializeObject <Event>(await File.ReadAllTextAsync(eventFilePath), JsonSettings));
        }
Esempio n. 9
0
        public async Task <bool> AddEvent(OracleInfo eventId, string[] outcomes, RootedKeyPath?nonceKeyPath = null)
        {
            var evt = await GetEvent(eventId);

            if (evt is Event)
            {
                return(false);
            }
            evt = new Event()
            {
                EventId      = eventId,
                Outcomes     = outcomes,
                NonceKeyPath = nonceKeyPath
            };
            await SaveEvent(evt);

            return(true);
        }
Esempio n. 10
0
        public async Task <DLCState> NewDLC(OracleInfo oracleInfo, DLCTransactionBuilder builder)
        {
            var dir = Path.Combine(RepositoryDirectory, "DLCs");

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            var s = new DLCState()
            {
                OracleInfo   = oracleInfo,
                BuilderState = builder.ExportStateJObject(),
                Id           = RandomUtils.GetUInt256()
            };
            var file = GetDLCFilePath(s.Id);
            await File.WriteAllTextAsync(file, JsonConvert.SerializeObject(s, JsonSettings));

            return(s);
        }
Esempio n. 11
0
        public async Task <EventFullName?> ResolveName(OracleInfo eventId)
        {
            var events = await NameRepository.GetIds(Scopes.Events);

            foreach (var ev in events)
            {
                var oracleId = new OracleId(eventId.PubKey);
                if (ev.Key.StartsWith(oracleId.ToString()))
                {
                    if (ev.Value == eventId.RValue.ToString())
                    {
                        var oracleName = await NameRepository.GetName(Scopes.Oracles, oracleId.ToString());

                        if (oracleName is null)
                        {
                            return(null);
                        }
                        var idx = ev.Key.IndexOf('/');
                        return(new EventFullName(oracleName, ev.Key.Substring(idx + 1)));
                    }
                }
            }
            return(null);
        }
Esempio n. 12
0
        public DLCTestVector(JObject testVector)
        {
            TestInputs       = testVector["testInputs"];
            Offer            = new Offer();
            Offer.OracleInfo = OracleInfo.Parse(
                TestInputs["params"]["oracleInfo"]["publicKey"].Value <string>() +
                TestInputs["params"]["oracleInfo"]["nonce"].Value <string>());
            var ci = new List <ContractInfo>();

            foreach (var jObj in (JArray)TestInputs["params"]["contractInfo"])
            {
                var info = new ContractInfo(new DiscreteOutcome(jObj["preImage"].Value <string>()), Money.Satoshis(jObj["localPayout"].Value <long>()));
                ci.Add(info);
                Assert.Equal(jObj["outcome"].Value <string>(), Encoders.Hex.EncodeData(info.Outcome.Hash));
            }
            Offer.ContractInfo = ci.ToArray();
            Offer.FeeRate      = new FeeRate(Money.Satoshis(TestInputs["params"]["feeRate"].Value <long>()), 1);
            Offer.ChainHash    = Network.RegTest.GenesisHash;
            Offer.Timeouts     = new Timeouts()
            {
                ContractMaturity = TestInputs["params"]["contractMaturityBound"].Value <uint>(),
                ContractTimeout  = TestInputs["params"]["contractTimeout"].Value <uint>()
            };
            ExpectedOfferTLV  = testVector["offer"].Value <string>();
            ExpectedAcceptTLV = testVector["accept"].Value <string>();
            ExpectedSignTLV   = testVector["sign"].Value <string>();
            JsonSerializerSettings settings = new JsonSerializerSettings();

            NBitcoin.JsonConverters.Serializer.RegisterFrontConverters(settings, Network.RegTest);
            UnsignedTxs = testVector["unsignedTxs"].ToObject <ExpectedTransactions>(JsonSerializer.Create(settings));
            SignedTxs   = testVector["signedTxs"].ToObject <ExpectedTransactions>(JsonSerializer.Create(settings));
            FillFundingInformation(Offer, "offerParams");
            OfferPrivateKey          = new Key(Encoders.Hex.DecodeData(TestInputs["offerParams"]["fundingPrivKey"].Value <string>()));
            Offer.PubKeys.FundingKey = OfferPrivateKey.PubKey;
            AcceptPrivateKey         = new Key(Encoders.Hex.DecodeData(TestInputs["acceptParams"]["fundingPrivKey"].Value <string>()));
        }
Esempio n. 13
0
 internal Oracle(OracleInfo info, List <string> latestTableSpaces)
 {
     this.info = info;
     this.latestTableSpaces = latestTableSpaces;
 }
Esempio n. 14
0
 internal async Task SetMapping(OracleInfo eventId, string name)
 {
     var fullname = GetEventFullName(eventId.PubKey, name);
     await NameRepository.SetMapping(Scopes.Events, fullname, eventId.RValue.ToString());
 }
Esempio n. 15
0
 internal Oracle(OracleInfo info)
 {
     this.info        = info;
     connectionString = new OracleConnectionStringBuilder(info.ConnectionString);
 }
Esempio n. 16
0
 internal Oracle(OracleInfo info)
 {
     this.info = info;
 }
Esempio n. 17
0
        public async Task <DiscreteOutcome?> AddAttestation(OracleInfo oracleInfo, Key oracleAttestation)
        {
            var oracle = await GetOracle(oracleInfo.PubKey);

            if (oracle is null)
            {
                return(null);
            }
            var evt = await GetEvent(oracleInfo.PubKey, oracleInfo.RValue);

            if (evt is null)
            {
                return(null);
            }
            var attestation = oracleAttestation.ToECPrivKey();
            var sig         = oracleInfo.RValue.CreateSchnorrSignature(attestation);

            if (sig is null)
            {
                return(null);
            }
            foreach (var outcome in evt.Outcomes)
            {
                var discreteOutcome = new DiscreteOutcome(outcome);
                if (!oracleInfo.PubKey.SigVerifyBIP340(sig, discreteOutcome.Hash))
                {
                    continue;
                }
                evt.Attestations ??= new Dictionary <string, Key>();
                if (!evt.Attestations.TryAdd(outcome, oracleAttestation))
                {
                    return(null);
                }
                // If we have two attestation for the same event, we can recover the private
                // key of the oracle
                if (evt.Attestations.Count > 1 && oracle.RootedKeyPath is null)
                {
                    var sigs = evt.Attestations.Select(kv => (Outcome: new DiscreteOutcome(kv.Key),
                                                              Signature: oracleInfo.RValue.CreateSchnorrSignature(kv.Value.ToECPrivKey()) ?? throw new InvalidOperationException("Invalid signature in attestations")))
                               .Take(2)
                               .ToArray();
                    if (!oracleInfo.PubKey.TryExtractPrivateKey(
                            sigs[0].Outcome.Hash, sigs[0].Signature,
                            sigs[1].Outcome.Hash, sigs[1].Signature, out var extracted) || extracted is null)
                    {
                        throw new InvalidOperationException("Could not recover the private key of the oracle, this should never happen");
                    }
                    var k = new Key(extracted.ToBytes());
                    oracle.RootedKeyPath = new RootedKeyPath(k.PubKey.GetHDFingerPrint(), new KeyPath());
                    await SaveOracle(oracle);

                    if (!KeySetExists(k.PubKey.GetHDFingerPrint()))
                    {
                        await SaveKeyset(k.PubKey.GetHDFingerPrint(), new Keyset()
                        {
                            SingleKey = k
                        });
                    }
                }
                await SaveEvent(evt);

                return(discreteOutcome);
            }
            return(null);
        }