protected override async Task InvokeAsyncBase(InvocationContext context)
        {
            EventFullName evt = context.GetEventName();

            if (await TryGetEvent(evt) is Event)
            {
                throw new CommandException("eventfullname", "This event already exists");
            }
            var outcomes = context.GetOutcomes();
            var oracle   = await this.GetOracle("eventfullname", evt.OracleName);

            if (oracle.RootedKeyPath is null)
            {
                throw new CommandException("eventfullname", "You do not own the keys of this oracle");
            }

            var k = await Repository.CreatePrivateKey();

            var nonce = k.PrivateKey.ToECPrivKey().CreateSchnorrNonce();
            var evtId = new OracleInfo(oracle.PubKey !, nonce);

            if (!await Repository.AddEvent(evtId, outcomes, k.KeyPath))
            {
                throw new CommandException("eventfullname", "This event already exists");
            }
            await NameRepository.AsEventRepository().SetMapping(evtId, evt.Name);

            context.Console.Out.Write(nonce.ToString());
        }
Exemple #2
0
        protected override async Task InvokeAsyncBase(InvocationContext context)
        {
            EventFullName evt    = context.GetEventName();
            var           rNonce = context.ParseResult.CommandResult.GetArgumentValueOrDefault <string>("nonce")?.ToLowerInvariant().Trim();

            if (rNonce is null)
            {
                throw new CommandOptionRequiredException("nonce");
            }
            if (!SchnorrNonce.TryParse(rNonce, out var nonce) || nonce is null)
            {
                throw new CommandException("nonce", "Invalid nonce");
            }

            var oracle = await GetOracle("eventfullname", evt.OracleName);

            var outcomes = context.GetOutcomes();
            var evtId    = new OracleInfo(oracle.PubKey !, nonce);

            if (!await Repository.AddEvent(evtId, outcomes.ToArray()))
            {
                throw new CommandException("eventfullname", "The specified event already exists");
            }
            await NameRepository.AsEventRepository().SetMapping(evtId, evt.Name);
        }
Exemple #3
0
        protected override async Task InvokeAsyncBase(InvocationContext context)
        {
            var attestation = context.ParseResult.CommandResult.GetArgumentValueOrDefault <string>("attestation")?.Trim();

            if (attestation is null)
            {
                throw new CommandOptionRequiredException("attestation");
            }
            var bytes = Encoders.Hex.DecodeData(attestation);

            if (bytes.Length != 32)
            {
                throw new CommandException("attestation", "The attestation must be 32 bytes");
            }
            var           attestationKey = new Key(bytes);
            EventFullName evt            = context.GetEventName();
            var           evtId          = await NameRepository.AsEventRepository().GetEventId(evt);

            if (evtId is null)
            {
                throw new CommandException("eventfullname", "This event's full name does not exist");
            }
            var outcome = await Repository.AddAttestation(evtId, attestationKey);

            if (outcome?.OutcomeString is null)
            {
                throw new CommandException("attestation", "This attestation does not attest known outcomes");
            }
            context.Console.Out.Write(outcome.OutcomeString);
        }
Exemple #4
0
        static void Main(string[] args)
        {
            ConsoleWriter writer = null;

            try                                                   //BugFix #2b
            {
                HttpClient httpClient = new HttpClient();

                JokeRepository jokeRepository = new JokeRepository(httpClient);
                NameRepository nameRepository = new NameRepository(httpClient);

                writer = new ConsoleWriter();
                IReader reader = new ConsoleReader(writer);

                UserQuestions    userQuestions    = new UserQuestions(reader, writer);
                UserInteractions userInteractions = new UserInteractions(writer, userQuestions);

                JokeService jokeService = new JokeService();

                ProgramRunner programRunner = new ProgramRunner(userInteractions, jokeRepository, nameRepository, jokeService);

                programRunner.Run();
            }
            catch (Exception)
            {
                if (writer != null)
                {
                    writer.WriteLine("Something went terribly wrong.");
                    writer.WriteLine("Are you sure you're connected to the internet?");
                }
            }
        }
    public void Main()
    {
        NameRepository nameRepository = new NameRepository();

        for (var temp = nameRepository.GetIterator(); temp.HasNext();)
        {
            Console.WriteLine("name:" + (string)temp.Next());
        }
    }
Exemple #6
0
        protected override async Task InvokeAsyncBase(InvocationContext context)
        {
            var dlcs = await NameRepository.AsDLCNameRepository().GetNames();

            foreach (var name in dlcs.OrderBy(n => n))
            {
                context.Console.Out.WriteLine(name);
            }
        }
 public DisplayTextService(NewTextEventRepository newTextEventRepository,
                           DialogueModel dialogueModel, DialogueContainerMarker dialogueContainerMarker,
                           NameRepository nameRepository)
 {
     this.newTextEventRepository  = newTextEventRepository ?? throw new ArgumentNullException(nameof(newTextEventRepository));
     this.dialogueContainerMarker = dialogueContainerMarker ?? throw new ArgumentNullException(nameof(dialogueContainerMarker));
     this.dialogueModel           = dialogueModel ?? throw new ArgumentNullException(nameof(dialogueModel));
     this.nameRepository          = nameRepository ?? throw new ArgumentNullException(nameof(nameRepository));
 }
Exemple #8
0
        protected override async Task InvokeAsyncBase(InvocationContext context)
        {
            var name = context.ParseResult.CommandResult.GetArgumentValueOrDefault <string>("name")?.Trim();

            if (name is null)
            {
                throw new CommandOptionRequiredException("name");
            }
            if (await this.TryGetDLC(name) != null)
            {
                throw new CommandException("name", "This DLC already exists");
            }
            EventFullName evtName = context.GetEventName();
            var           oracle  = await GetOracle("eventfullname", evtName.OracleName);

            if (oracle?.PubKey is null)
            {
                throw new CommandException("eventfullname", "The specified oracle does not exists");
            }
            var evt = await GetEvent("eventfullname", evtName);

            var payoffsStr = context.ParseResult.CommandResult.GetArgumentValueOrDefault <List <string> >("payoff");

            if (payoffsStr is null || payoffsStr.Count == 0)
            {
                throw new CommandOptionRequiredException("payoff");
            }
            var payoffs = CreatePayoffs(payoffsStr);

            FixCasing(evt, payoffs);
            var builder = new DLCTransactionBuilder(true, null, null, null, Network);

            var timeout = new Timeouts()
            {
                ContractMaturity = 0,
                ContractTimeout  = Constants.NeverLockTime
            };

            if (context.ParseResult.HasOption("cetlocktime"))
            {
                timeout.ContractMaturity = new LockTime(context.ParseResult.ValueForOption <uint>("cetlocktime"));
            }
            if (context.ParseResult.HasOption("refundlocktime"))
            {
                timeout.ContractTimeout = new LockTime(context.ParseResult.ValueForOption <uint>("refundlocktime"));
            }
            var collateral = payoffs.CalculateMinimumCollateral();

            builder.Offer(oracle.PubKey, evt.EventId !.RValue, payoffs, timeout);
            var dlc = await Repository.NewDLC(evt.EventId, builder);

            await NameRepository.AsDLCNameRepository().SetMapping(name, dlc.LocalId);

            context.Console.Out.Write($"Offer created, you now need to setup the DLC sending {collateral} BTC to yourself. For more information, run `dlc show \"{name}\"`.");
        }
Exemple #9
0
        protected override async Task InvokeAsyncBase(InvocationContext context)
        {
            var outcome = context.ParseResult.CommandResult.GetArgumentValueOrDefault <string>("outcome")?.Trim();
            var force   = context.ParseResult.ValueForOption <bool>("force");

            if (outcome is null)
            {
                throw new CommandOptionRequiredException("outcome");
            }
            EventFullName evt   = context.GetEventName();
            var           evtId = await NameRepository.AsEventRepository().GetEventId(evt);

            if (evtId is null)
            {
                throw new CommandException("eventfullname", "This event's full name does not exist");
            }
            var oracle = await GetOracle("eventfullname", evt.OracleName);

            var discreteOutcome = new DiscreteOutcome(outcome);
            var evtObj          = await GetEvent("eventfullname", evt);

            if (evtObj?.NonceKeyPath is null)
            {
                throw new CommandException("eventfullname", "You did not generated this event");
            }
            outcome = evtObj.Outcomes.FirstOrDefault(o => o.Equals(outcome, StringComparison.OrdinalIgnoreCase));
            if (outcome is null)
            {
                throw new CommandException("outcome", "This outcome does not exists in this event");
            }
            var key = oracle.RootedKeyPath is RootedKeyPath ? await Repository.GetKey(oracle.RootedKeyPath) : null;

            if (key is null)
            {
                throw new CommandException("eventfullname", "You do not own the keys of this oracle");
            }
            if (evtObj.Attestations?.ContainsKey(outcome) is true)
            {
                throw new CommandException("outcome", "This outcome has already been attested");
            }
            if (evtObj.Attestations != null && evtObj.Attestations.Count > 0 && !force)
            {
                throw new CommandException("outcome", "An outcome has already been attested, attesting another one could leak the private key of your oracle. Use -f to force your action.");
            }
            var kValue = await Repository.GetKey(evtObj.NonceKeyPath);

            key.ToECPrivKey().TrySignBIP140(discreteOutcome.Hash, new PrecomputedNonceFunctionHardened(kValue.ToECPrivKey().ToBytes()), out var sig);
            var oracleAttestation = new Key(sig !.s.ToBytes());

            if (await Repository.AddAttestation(evtId, oracleAttestation) != new DiscreteOutcome(outcome))
            {
                throw new InvalidOperationException("Error while validating reveal");
            }
            context.Console.Out.Write(oracleAttestation.ToHex());
        }
 public ProgramRunner(
     UserInteractions userInteractions,
     JokeRepository jokeRepository,
     NameRepository nameRepository,
     JokeService jokeService)
 {
     this.userInteractions = userInteractions;
     this.jokeRepository   = jokeRepository;
     this.nameRepository   = nameRepository;
     this.jokeService      = jokeService;
 }
Exemple #11
0
 public string[] GetAllNameIds()
 {
     try
     {
         return(NameRepository.GetAllIds());
     }
     catch (Exception ex)
     {
         throw new Exception($"Failed to get all Name ids with exception: {ex.Message}");
     }
 }
Exemple #12
0
 public NameDTO GetById(string id)
 {
     try
     {
         return(NameRepository.GetById(id));
     }
     catch (Exception ex)
     {
         throw new Exception($"Failed to get Name by Id {id} with exception: {ex.Message}");
     }
 }
Exemple #13
0
        private void btIteratorPattern_Click(object sender, EventArgs e)
        {
            string         str             = "";
            NameRepository namesRepository = new NameRepository();

            for (IIterator iter = namesRepository.getIterator(); iter.hasNext();)
            {
                String name = (String)iter.next();
                str += "Name : " + name + "\r\n";
            }
            tbOutWindow.Text = str;
        }
Exemple #14
0
        protected override async Task InvokeAsyncBase(InvocationContext context)
        {
            var oracleName = context.ParseResult.ValueForOption <string>("oracle");

            foreach (var evtName in (await NameRepository
                                     .AsEventRepository()
                                     .ListEvents(oracleName))
                     .OrderBy(o => o.ToString()))
            {
                context.Console.Out.WriteLine(evtName.ToString());
            }
        }
        static void Main(string[] args)
        {
            //何时使用:遍历一个聚合对象。

            NameRepository repository = new NameRepository();

            for (IIterator iter = repository.getIterator(); iter.hasNext();)
            {
                String name = (String)iter.next();
                Console.WriteLine("Name : " + name);
            }

            Console.ReadKey();
        }
Exemple #16
0
        public static void Run()
        {
            var repository = new NameRepository();
            var iterator   = repository.GetIterator();

            Console.WriteLine("<Iterator Pattern Example>");
            Console.WriteLine();
            while (iterator.HasNext())
            {
                Console.WriteLine("\t" + iterator.Next());
            }
            Console.WriteLine();
            Console.WriteLine("</Iterator Pattern Example>");
            Console.WriteLine();
        }
        public static void loadNames(BookContext context)
        {
            NameRepository repo = new NameRepository(context);

            repo.insertName(new Name()
            {
                FirstName = "Mahesh",
                LastName  = "Mahadeva"
            });
            repo.insertName(new Name()
            {
                FirstName = "BB",
                LastName  = "MM"
            });
        }
Exemple #18
0
        //Fetch values from diverse sheets
        private static TypeMatchup InitiateTypeMatchup(TypeMatchup matchup)
        {
            foreach (var type in TypeRepository.GetAllTypes())
            {
                if (matchup.AttackingTypeId == type.TypeId)
                {
                    matchup.AttackingType = NameRepository.getNameFromId(type.NameId);
                }
                if (matchup.DefendingTypeId == type.TypeId)
                {
                    matchup.DefendingType = NameRepository.getNameFromId(type.NameId);
                }
            }

            return(matchup);
        }
 public StartDialogueService(
     StartDialogueEventRepository startDialogueEventRepository,
     DialogueRepository dialogueRepository,
     string npcId,
     Sprite iconForDialogue,
     IconForDialogueRepository iconForDialogueRepository,
     NameRepository nameRepository,
     Dialogue dialogue)
 {
     this.startDialogueEventRepository = startDialogueEventRepository ?? throw new ArgumentNullException(nameof(startDialogueEventRepository));
     this.dialogueRepository           = dialogueRepository ?? throw new ArgumentNullException(nameof(dialogueRepository));
     this.npcId                     = npcId ?? throw new ArgumentNullException(nameof(npcId));
     this.iconForDialogue           = iconForDialogue;
     this.iconForDialogueRepository = iconForDialogueRepository ?? throw new ArgumentNullException(nameof(iconForDialogueRepository));
     this.nameRepository            = nameRepository ?? throw new ArgumentNullException(nameof(nameRepository));
     this.dialogue                  = dialogue;
 }
Exemple #20
0
        static void Main(string[] args)
        {
            _userName = NameRepository.GetRandomName();
            _client   = new TcpClient();
            Console.CancelKeyPress += CancelKeyHandler;
            try
            {
                _client.Connect(Host, Port);
                _stream = _client.GetStream();

                SendMessage(_userName);

                if (!IsTplVersion)
                {
                    var recieverThread = new Thread(ReceiveMessage);
                    recieverThread.Start();
                }
                else
                {
                    _recievertask = Task.Factory.StartNew(ReceiveMessage);
                }

                var messageNumber = MessageRepository.GetRandomMessageNumber();
                Console.WriteLine($"Random User Name = {_userName}, ({messageNumber} messages)");

                for (int i = 0; i < messageNumber; i++)
                {
                    Thread.Sleep(MilisecondsRepository.GetRandomMilisecondsNumber());
                    SendMessage(MessageRepository.GetRandomMessage());
                }

                if (IsTplVersion)
                {
                    _recievertask.Wait();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Disconnect();
            }
        }
Exemple #21
0
        static void Main(string[] args)
        {
            var nameRepo = new NameRepository();

            IElement[] elements = nameRepo.GetIElements();


            foreach (IElement element in elements)
            {
                if (element.IsOfType(element, "Car"))
                {
                }
                //Console.WriteLine(person);
                Console.WriteLine(
                    $"Elemento di nome {element.FullName}\n" +
                    $"di tipo {element.Type}");

                Console.ReadLine();
            }
        }
Exemple #22
0
 public GetDefaultService(NameRepository repository)
 {
     this.repository = repository;
 }
Exemple #23
0
 public NamesController(NameRepository nameRepository)
 {
     _nameRepository = nameRepository;
 }
Exemple #24
0
 public static void Init(string connectionString)
 {
     EventStoreFactory.Init(connectionString);
     InitializeDependencyInjection();
     NameRepository.Init(EventStoreFactory.GetConnection(), new NameProjector()).Wait();
 }
Exemple #25
0
        protected override async Task InvokeAsyncBase(InvocationContext context)
        {
            var offer = DLCHelpers.GetOffer(context, Repository.JsonSettings);
            var name  = context.ParseResult.CommandResult.GetArgumentValueOrDefault <string>("name")?.Trim();

            if (name is null)
            {
                throw new CommandOptionRequiredException("name");
            }
            if (await this.TryGetDLC(name) != null)
            {
                throw new CommandException("name", "This DLC already exists");
            }
            if (offer.OracleInfo is null)
            {
                throw new CommandException("offer", "Missing oracleInfo");
            }
            if (offer.Timeouts is null)
            {
                throw new CommandException("offer", "Missing timeouts");
            }
            if (offer.ContractInfo is null)
            {
                throw new CommandException("offer", "Missing contractInfos");
            }

            var oracle = await Repository.GetOracle(offer.OracleInfo.PubKey);

            if (oracle is null)
            {
                throw new CommandException("offer", "Unknown oracle");
            }
            var evt = await Repository.GetEvent(offer.OracleInfo.PubKey, offer.OracleInfo.RValue);

            if (evt is null)
            {
                throw new CommandException("offer", "Unknown event");
            }

            var maturity = new LockTimeEstimation(offer.Timeouts.ContractMaturity, Network);
            var refund   = new LockTimeEstimation(offer.Timeouts.ContractTimeout, Network);

            if (!refund.UnknownEstimation)
            {
                if (refund.EstimatedRemainingBlocks == 0)
                {
                    throw new CommandException("offer", "The refund should not be immediately valid");
                }
                if (refund.EstimatedRemainingBlocks < maturity.EstimatedRemainingBlocks)
                {
                    throw new CommandException("offer", "The refund should not be valid faster than the contract execution transactions");
                }
            }

            offer.SetContractPreimages(evt.Outcomes);
            try
            {
                var builder = new DLCTransactionBuilder(false, null, null, null, Network);
                builder.Accept(offer);
                var dlc = await Repository.NewDLC(offer.OracleInfo, builder);

                dlc.BuilderState = builder.ExportStateJObject();
                dlc.Offer        = JObject.FromObject(offer, JsonSerializer.Create(Repository.JsonSettings));
                await NameRepository.AsDLCNameRepository().SetMapping(name, dlc.Id);

                await Repository.SaveDLC(dlc);

                context.Console.Out.Write($"Contract accepted, you now need to setup the DLC. For more information, run `dlc show \"{name}\"`.");
            }
            catch (Exception ex)
            {
                throw new CommandException("offer", $"Invalid offer or PSBT. ({ex.Message})");
            }
        }
Exemple #26
0
        protected override async Task InvokeAsyncBase(InvocationContext context)
        {
            var name = context.ParseResult.CommandResult.GetArgumentValueOrDefault <string>("name")?.Trim();

            if (name is null)
            {
                throw new CommandOptionRequiredException("name");
            }

            var dlc = await GetDLC("name", name);

            if (dlc?.BuilderState is null ||
                dlc?.OracleInfo is null)
            {
                throw new CommandException("name", "This DLC does not exist");
            }

            var oracle = await Repository.GetOracle(dlc.OracleInfo.PubKey);

            string?oracleName = null;

            EventFullName eventName = new EventFullName("???", "???");

            if (oracle != null)
            {
                oracleName = await NameRepository.GetName(Scopes.Oracles, new OracleId(dlc.OracleInfo.PubKey).ToString());

                var ev = await Repository.GetEvent(dlc.OracleInfo);

                eventName = await NameRepository.AsEventRepository().ResolveName(dlc.OracleInfo) ?? eventName;
            }
            var shown = ParseShownItem(context);

            if (shown == ShowOption.DLC)
            {
                context.Console.Out.WriteLine($"Name: {name}");
                context.Console.Out.WriteLine($"Local Id: {dlc.Id}");
                var builder = new DLCTransactionBuilder(dlc.BuilderState.ToString(), Network);
                var role    = builder.State.IsInitiator ? "Offerer" : "Acceptor";
                context.Console.Out.WriteLine($"Event: {eventName}");
                context.Console.Out.WriteLine($"Role: {role}");
                var nextStep = dlc.GetNextStep(Network);
                context.Console.Out.WriteLine($"Next step: {nextStep}");
                context.Console.Out.WriteLine($"Next step explanation:");
                context.Console.Out.Write($"{Explain(nextStep, name, builder.State)}");
            }
            else if (shown == ShowOption.Offer)
            {
                if (dlc.Offer is null)
                {
                    throw new CommandException("offer", "No offer available for this DLC");
                }
                context.WriteObject(dlc.Offer, Repository.JsonSettings);
            }
            else if (shown == ShowOption.Accept)
            {
                if (dlc.Accept is null)
                {
                    throw new CommandException("offer", "No accept message available for this DLC");
                }
                context.WriteObject(dlc.Accept, Repository.JsonSettings);
            }
            else if (shown == ShowOption.Funding)
            {
                try
                {
                    var builder = new DLCTransactionBuilder(dlc.BuilderState.ToString(), Network);
                    context.WritePSBT(builder.GetFundingPSBT());
                }
                catch
                {
                    throw new CommandException("funding", "No funding PSBT ready for this DLC");
                }
            }
            else if (shown == ShowOption.Abort)
            {
                if (dlc.Abort is null)
                {
                    throw new CommandException("abort", "No abort PSBT for this DLC");
                }
                context.WritePSBT(dlc.Abort);
            }
            else if (shown == ShowOption.Refund)
            {
                try
                {
                    var builder = new DLCTransactionBuilder(dlc.BuilderState.ToString(), Network);
                    context.WriteTransaction(builder.BuildRefund(), Network);
                }
                catch
                {
                    throw new CommandException("refund", "No refund PSBT ready for this DLC");
                }
            }
            else
            {
                throw new NotSupportedException();
            }
        }
Exemple #27
0
 public PostContainsService(NameRepository repository)
 {
     this.repository = repository;
 }
 public PersonNameGenerator()
 {
     _nameRepository   = new RepositoryFactory().CreateNameRepository();
     _numberRandomizer = new NumberRandomizer();
 }
Exemple #29
0
        protected override async Task InvokeAsyncBase(InvocationContext context)
        {
            var offer = context.GetOffer(Network);

            if (offer.OracleInfo is null)
            {
                throw new CommandException("offer", "Missing oracleInfo");
            }
            if (offer.Timeouts is null)
            {
                throw new CommandException("offer", "Missing timeouts");
            }
            if (offer.ContractInfo is null)
            {
                throw new CommandException("offer", "Missing contractInfos");
            }
            var oracle = await Repository.GetOracle(offer.OracleInfo.PubKey);

            var oracleName = await NameRepository.GetName(Scopes.Oracles, new OracleId(offer.OracleInfo.PubKey).ToString());

            if (oracle is null || oracleName is null)
            {
                throw new CommandException("offer", "Unknown oracle");
            }

            var evt = await Repository.GetEvent(offer.OracleInfo.PubKey, offer.OracleInfo.RValue);

            if (evt?.EventId is null)
            {
                throw new CommandException("offer", "Unknown event");
            }

            var maturity = new LockTimeEstimation(offer.Timeouts.ContractMaturity, Network);
            var refund   = new LockTimeEstimation(offer.Timeouts.ContractTimeout, Network);

            if (!refund.UnknownEstimation)
            {
                if (refund.EstimatedRemainingBlocks == 0)
                {
                    throw new CommandException("offer", "The refund should not be immediately valid");
                }
                if (refund.EstimatedRemainingBlocks < maturity.EstimatedRemainingBlocks)
                {
                    throw new CommandException("offer", "The refund should not be valid faster than the contract execution transactions");
                }
            }
            if (!offer.SetContractPreimages(evt.Outcomes))
            {
                throw new CommandException("offer", "The contract info of the offer does not match the specification of the event");
            }
            try
            {
                var review  = new OfferReview(offer);
                var evtName = (await NameRepository.AsEventRepository().ResolveName(evt.EventId)) ?? new EventFullName("???", "???");
                context.Console.Out.WriteLine($"Event: {evtName}");
                context.Console.Out.WriteLine($"Fee rate: {offer.FeeRate!.SatoshiPerByte} sat/vbyte");
                context.Console.Out.WriteLine($"The payoff function if you accept:");
                PrintPayoffs(context, review.AcceptorPayoffs);
                context.Console.Out.WriteLine($"Your expected collateral: {review.AcceptorCollateral.ToString(false, false)}");
                context.Console.Out.WriteLine($"Contract Execution validity: " + maturity.ToString());
                context.Console.Out.WriteLine($"Refund validity: " + refund.ToString());
                context.Console.Out.WriteLine($"How to accept this offer:");
                context.Console.Out.WriteLine($"If your plan to accept this offer, you need to run 'dlc accept <dlcname> <offer>'. The DLC name is arbitrary and local, you will use it to manage your DLC.");
            }
            catch (Exception ex)
            {
                throw new CommandException("offer", $"Invalid offer. ({ex.Message})");
            }
        }
Exemple #30
0
 public NameService(NameRepository nameRepository)
 {
     _nameRepository = nameRepository;
 }