예제 #1
0
 public void NotBoolean_Execute_CorrectResultValue()
 {
     TestPureUnaryBooleanOperation(Signatures.DefinePureUnaryFunction("Not", NITypes.Boolean, NITypes.Boolean), true, false);
 }
예제 #2
0
 public void AccumulateNotBoolean_Execute_CorrectResultValue()
 {
     TestMutatingUnaryBooleanOperation(Signatures.DefineMutatingUnaryFunction("AccumulateNot", NITypes.Boolean), true, false);
 }
예제 #3
0
 private void button5_Click(object sender, EventArgs e)
 {
     Signatures.PrintSignatures();
 }
        public override APIResultCodes Authorize <T>(ref T tblock)
        {
            if (!(tblock is SendTransferBlock))
            {
                return(APIResultCodes.InvalidBlockType);
            }

            var block = tblock as SendTransferBlock;

            // 1. check if the account already exists
            if (!_accountCollection.AccountExists(block.AccountID))
            {
                return(APIResultCodes.AccountDoesNotExist);
            }

            TransactionBlock lastBlock = _accountCollection.FindLatestBlock(block.AccountID);

            if (lastBlock == null)
            {
                return(APIResultCodes.CouldNotFindLatestBlock);
            }

            var result = VerifyBlock(block, lastBlock);

            if (result != APIResultCodes.Success)
            {
                return(result);
            }

            //if (lastBlock.Balances[LyraGlobal.LYRA_TICKER_CODE] <= block.Balances[LyraGlobal.LYRA_TICKER_CODE] + block.Fee)
            //    return AuthorizationResultCodes.NegativeTransactionAmount;

            // Validate the destination account id
            if (!Signatures.ValidateAccountId(block.DestinationAccountId))
            {
                return(APIResultCodes.InvalidDestinationAccountId);
            }

            result = VerifyTransactionBlock(block);
            if (result != APIResultCodes.Success)
            {
                return(result);
            }

            if (!block.ValidateTransaction(lastBlock))
            {
                return(APIResultCodes.SendTransactionValidationFailed);
            }

            result = ValidateNonFungible(block, lastBlock);
            if (result != APIResultCodes.Success)
            {
                return(result);
            }

            Sign(ref block);

            _accountCollection.AddBlock(block);

            return(base.Authorize(ref tblock));
        }
예제 #5
0
        public async Task <string> SignAPICallAsync()
        {
            var syncInfo = await _client.GetSyncHeight();

            return(Signatures.GetSignature(NodeService.Instance.PosWallet.PrivateKey, syncInfo.SyncHash, NodeService.Instance.PosWallet.AccountId));
        }
        private void StartInit()
        {
            if (0 == GetBlockCount() && NodeService.Instance.PosWallet.AccountId ==
                ProtocolSettings.Default.StandbyValidators[0])
            {
                // do genesis
                var authGenesis = new ServiceBlock
                {
                    Index              = 1,
                    UIndex             = 1,
                    NetworkId          = _nodeConfig.Lyra.NetworkId,
                    ShardId            = "Primary",
                    TransferFee        = 1,
                    TokenGenerationFee = 100,
                    TradeFee           = 0.1m,
                    SvcAccountID       = NodeService.Instance.PosWallet.AccountId
                };
                authGenesis.InitializeBlock(null, NodeService.Instance.PosWallet.PrivateKey,
                                            _nodeConfig.Lyra.NetworkId, authGenesis.ShardId,
                                            NodeService.Instance.PosWallet.AccountId);
                authGenesis.UHash          = SignableObject.CalculateHash($"{authGenesis.UIndex}|{authGenesis.Index}|{authGenesis.Hash}");
                authGenesis.Authorizations = new List <AuthorizationSignature>();
                authGenesis.Authorizations.Add(new AuthorizationSignature
                {
                    Key       = NodeService.Instance.PosWallet.AccountId,
                    Signature = Signatures.GetSignature(NodeService.Instance.PosWallet.PrivateKey, authGenesis.Hash, NodeService.Instance.PosWallet.AccountId)
                });
                // TODO: add more seed's auth info

                _store.AddBlock(authGenesis);

                // the first consolidate block
                var consBlock = new ConsolidationBlock
                {
                    UIndex       = 2,
                    NetworkId    = authGenesis.NetworkId,
                    ShardId      = authGenesis.ShardId,
                    ServiceHash  = authGenesis.Hash,
                    SvcAccountID = NodeService.Instance.PosWallet.AccountId
                };
                consBlock.InitializeBlock(authGenesis, NodeService.Instance.PosWallet.PrivateKey,
                                          _nodeConfig.Lyra.NetworkId, authGenesis.ShardId,
                                          NodeService.Instance.PosWallet.AccountId);
                consBlock.UHash          = SignableObject.CalculateHash($"{consBlock.UIndex}|{consBlock.Index}|{consBlock.Hash}");
                consBlock.Authorizations = new List <AuthorizationSignature>();
                consBlock.Authorizations.Add(new AuthorizationSignature
                {
                    Key       = NodeService.Instance.PosWallet.AccountId,
                    Signature = Signatures.GetSignature(NodeService.Instance.PosWallet.PrivateKey, consBlock.Hash + consBlock.ServiceHash, NodeService.Instance.PosWallet.AccountId)
                });

                _store.AddBlock(consBlock);

                // tell consensus what happened
                InSyncing = false;

                var board = new BillBoard();
                board.Add(NodeService.Instance.PosWallet.AccountId);   // add me!

                LyraSystem.Singleton.Consensus.Tell(board);
                LyraSystem.Singleton.Consensus.Tell(new ConsensusService.BlockChainSynced());
                _log.LogInformation("Service Genesis Completed.");
            }
            else
            {
                SyncBlocksFromSeeds(0);
            }
        }
 public Signature GetById(int id)
 {
     // try to find the signature by the id
     return(Signatures.FirstOrDefault(s => s.Id == id));
 }
예제 #8
0
 public void GenerateWallet()
 {
     (_privatekey, _accountid) = Signatures.GenerateWallet();
 }
예제 #9
0
 public Signature GetSignatureFor(Signer signer)
 {
     return(Signatures.Find(elem => signer.Identifier.IsSameAs(elem.Identifier)));
 }
        protected override async Task <APIResultCodes> AuthorizeImplAsync <T>(DagSystem sys, T tblock)
        {
            if (!(tblock is TokenGenesisBlock))
            {
                return(APIResultCodes.InvalidBlockType);
            }

            var block = tblock as TokenGenesisBlock;

            // Local node validations - before it sends it out to the authorization sample:
            // 1. check if the account already exists
            if (!(tblock is LyraTokenGenesisBlock))
            {
                if (!await sys.Storage.AccountExistsAsync(block.AccountID))
                {
                    return(APIResultCodes.AccountDoesNotExist); //
                }
                TransactionBlock lastBlock = await sys.Storage.FindLatestBlockAsync(block.AccountID) as TransactionBlock;

                if (lastBlock == null)
                {
                    return(APIResultCodes.CouldNotFindLatestBlock);
                }

                // check LYR balance
                if (lastBlock.Balances[LyraGlobal.OFFICIALTICKERCODE] != block.Balances[LyraGlobal.OFFICIALTICKERCODE] + block.Fee.ToBalanceLong())
                {
                    return(APIResultCodes.InvalidNewAccountBalance);
                }

                // check ticker name
                // https://www.quora.com/What-characters-are-not-allowed-in-a-domain-name
                var r = new Regex(@"[^\w-]|^-|-$");
                if (!block.Ticker.Contains(block.DomainName + "/") || r.IsMatch(block.DomainName))
                {
                    return(APIResultCodes.InvalidDomainName);
                }

                if (r.IsMatch(block.Ticker.Replace(block.DomainName + "/", "")))
                {
                    return(APIResultCodes.InvalidTickerName);
                }

                if (block.RenewalDate > DateTime.UtcNow.Add(TimeSpan.FromDays(3660)) || block.RenewalDate < DateTime.UtcNow)
                {
                    return(APIResultCodes.InvalidTokenRenewalDate);
                }

                if (string.IsNullOrWhiteSpace(block.DomainName))
                {
                    return(APIResultCodes.EmptyDomainName);
                }

                bool tokenIssuerIsSeed0 = block.AccountID == ProtocolSettings.Default.StandbyValidators[0];
                if (!tokenIssuerIsSeed0 && block.AccountID != LyraGlobal.GetDexServerAccountID(LyraNodeConfig.GetNetworkId()))
                {
                    if (block.DomainName.Length < 6)
                    {
                        return(APIResultCodes.DomainNameTooShort);
                    }
                    if (_reservedDomains.Any(a => a.Equals(block.DomainName, StringComparison.InvariantCultureIgnoreCase)))
                    {
                        return(APIResultCodes.DomainNameReserved);
                    }
                }
            }

            if (await sys.Storage.WasAccountImportedAsync(block.AccountID))
            {
                return(APIResultCodes.CannotModifyImportedAccount);
            }

            var tresult = await VerifyTransactionBlockAsync(sys, block);

            if (tresult != APIResultCodes.Success)
            {
                return(tresult);
            }

            // check length
            if (string.IsNullOrWhiteSpace(block.DomainName) || string.IsNullOrWhiteSpace(block.Ticker))
            {
                return(APIResultCodes.InvalidTickerName);
            }

            if (block.DomainName.Length >= 64 || block.Ticker.Length >= 64)
            {
                return(APIResultCodes.InvalidTickerName);
            }

            // check if this token already exists
            //AccountData genesis_blocks = _accountCollection.GetAccount(AccountCollection.GENESIS_BLOCKS);
            //if (genesis_blocks.FindTokenGenesisBlock(testTokenGenesisBlock) != null)
            if (await sys.Storage.FindTokenGenesisBlockAsync(block.Hash, block.Ticker) != null)
            {
                return(APIResultCodes.TokenGenesisBlockAlreadyExists);
            }

            if (block.Fee != (await sys.Storage.GetLastServiceBlockAsync()).TokenGenerationFee)
            {
                return(APIResultCodes.InvalidFeeAmount);
            }

            if (block.NonFungibleType == NonFungibleTokenTypes.Collectible && !block.IsNonFungible)
            {
                return(APIResultCodes.InvalidNFT);
            }

            if (block.IsNonFungible)
            {
                if (!Signatures.ValidateAccountId(block.NonFungibleKey))
                {
                    return(APIResultCodes.InvalidNonFungiblePublicKey);
                }

                // Validate Collectible NFT
                if (block.ContractType == ContractTypes.Collectible)
                {
                    if (block.Precision != 0)
                    {
                        return(APIResultCodes.InvalidNFT);
                    }

                    if (block.NonFungibleType != NonFungibleTokenTypes.Collectible)
                    {
                        return(APIResultCodes.InvalidNFT);
                    }
                }
            }

            return(await Lyra.Shared.StopWatcher.TrackAsync(() => base.AuthorizeImplAsync(sys, tblock), "TokenGenesisAuthorizer->ReceiveTransferAuthorizer"));
        }
        private async Task <string> SignAPIAsync()
        {
            var lsb = await client.GetLastServiceBlockAsync();

            return(Signatures.GetSignature(PRIVATE_KEY_1, lsb.GetBlock().Hash, ADDRESS_ID_1));
        }
        private SemaphoreSlim semaphore = new SemaphoreSlim(1);      // we need to run tests in serial

        public static TransitWallet Restore(string privateKey)
        {
            var accountId = Signatures.GetAccountIdFromPrivateKey(privateKey);

            return(new TransitWallet(accountId, privateKey, LyraRestClient.Create(TestConfig.networkId, "Windows", "UnitTest", "1.0")));
        }
예제 #13
0
 protected FileType AddSignatures(params byte[][] bytes)
 {
     Signatures.AddRange(bytes);
     return(this);
 }
예제 #14
0
        public bool Match(Signatures.ISignature sig)
        {
            // match schema if given
            if (!String.IsNullOrEmpty(Schema) &&
                !String.Equals(sig.Schema, Schema, StringComparison.InvariantCultureIgnoreCase))
                return false;

            // match and remove prefix if given
            var nm = sig.Name;
            if (!String.IsNullOrEmpty(Prefix))
            {
                if (!nm.StartsWith(Prefix)) return false;
                nm = nm.Substring(Prefix.Length);
            }

            // match pattern if also given
            if (!String.IsNullOrEmpty(Pattern) &&
                !GetRegex().IsMatch(nm))
                return false;

            return true;
        }
예제 #15
0
        private async void BotOnMessageReceived(object sender, MessageEventArgs messageEventArgs)
        {
            var message = messageEventArgs.Message;

            if (message == null || message.Type != MessageType.Text || !message.Text.StartsWith('/'))
            {
                return;
            }

            var args = message.Text.Split(' ', '@');

            switch (args.First())
            {
            case "/height":
                await SendHeight(message.Chat.Id);

                break;

            case "/nodes":
                try
                {
                    await SendNodesInfoToGroupAsync(message.Chat.Id);
                }
                catch (Exception ex)
                {
                    await SendGroupMessageAsync(message.Chat.Id, $"Error: {ex.Message}");
                }
                break;

            case "/tps":
                await SendGroupMessageAsync(message.Chat.Id, "No Data");

                break;

            case "/send":
                if (args.Length == 2 && Signatures.ValidateAccountId(args[1]))
                {
                    var ret = await SendEvalCoin(args.Skip(1).First());
                    await SendGroupMessageAsync(message.Chat.Id, ret);
                }
                else
                {
                    await SendGroupMessageAsync(message.Chat.Id, "*Example*\n\n/send [[your wallet address here]]");
                }
                break;

            case "/help":
                const string usage = @"
*User Command*:
/height   - display Lyra BlockChain Height
/nodes    - send status of all nodes
/tps      - send info about TPS
/send     - send testnet Lyra Coin to address
/help     - display this message";
//*Authorizer Node Owner Command*:
///authlist _AccountId_ _SignedMessage_ - List a node to authorizers list
///authdelist _AccountId_ _SignedMessage_ - Delist a node from authorizers list
//*Admim Command*:
///seed _AccountId_ - approve a authorizer node to seed node
///deseed _AccountId_ - disapprove a seed node
//";
                await SendGroupMessageAsync(message.Chat.Id, usage);

                break;

            case "/authlist":
            case "/authdelist":
                await SendGroupMessageAsync(message.Chat.Id, "Under Construction");

                break;

            case "/seed":
            case "/deseed":
                if (message.From.Id == 397968968)         // @jfkwn
                {
                    await SendGroupMessageAsync(message.Chat.Id, "Code todo");
                }
                else
                {
                    await SendGroupMessageAsync(message.Chat.Id, "Only admins can do this");
                }
                break;

            default:
                await SendGroupMessageAsync(message.Chat.Id, "Unknown command. Please reference to: /help");

                break;
            }
        }
예제 #16
0
 public static (string privateKey, string accountId) GenerateWalletKey()
 {
     return(Signatures.GenerateWallet());
 }
        public override APIResultCodes Authorize <T>(ref T tblock)
        {
            if (!(tblock is TokenGenesisBlock))
            {
                return(APIResultCodes.InvalidBlockType);
            }

            var block = tblock as TokenGenesisBlock;

            // Local node validations - before it sends it out to the authorization sample:
            // 1. check if the account already exists
            if (!_accountCollection.AccountExists(block.AccountID))
            {
                return(APIResultCodes.AccountDoesNotExist); //
            }
            TransactionBlock lastBlock = _accountCollection.FindLatestBlock(block.AccountID);

            if (lastBlock == null)
            {
                return(APIResultCodes.CouldNotFindLatestBlock);
            }

            // 2. Validate blocks
            var result = VerifyBlock(block, lastBlock);

            if (result != APIResultCodes.Success)
            {
                return(result);
            }

            result = VerifyTransactionBlock(block);
            if (result != APIResultCodes.Success)
            {
                return(result);
            }

            // check LYR balance
            if (lastBlock.Balances[LyraGlobal.LYRA_TICKER_CODE] != block.Balances[LyraGlobal.LYRA_TICKER_CODE] + block.Fee)
            {
                return(APIResultCodes.InvalidNewAccountBalance);
            }

            // check if this token already exists
            //AccountData genesis_blocks = _accountCollection.GetAccount(AccountCollection.GENESIS_BLOCKS);
            //if (genesis_blocks.FindTokenGenesisBlock(testTokenGenesisBlock) != null)
            if (_accountCollection.FindTokenGenesisBlock(block.Hash, block.Ticker) != null)
            {
                return(APIResultCodes.TokenGenesisBlockAlreadyExists);
            }

            if (block.Fee != _serviceAccount.GetLastServiceBlock().TokenGenerationFee)
            {
                return(APIResultCodes.InvalidFeeAmount);
            }

            if (block.IsNonFungible)
            {
                if (!Signatures.ValidateAccountId(block.NonFungibleKey))
                {
                    return(APIResultCodes.InvalidNonFungiblePublicKey);
                }
            }

            if (block.RenewalDate > DateTime.Now.Add(TimeSpan.FromDays(366)) || block.RenewalDate < DateTime.Now)
            {
                return(APIResultCodes.InvalidTokenRenewalDate);
            }

            // sign with the authorizer key
            Sign(ref block);

            _accountCollection.AddBlock(block);

            return(base.Authorize(ref tblock));
        }
예제 #18
0
        public ActionResult Details(string id)
        {
            Signatures temp = db.Signatures.Find(int.Parse(id));

            return(View("Details", temp));
        }
예제 #19
0
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private Signatures BuildSignatures(SignatureParameters signatureParameters)
        {
            //Entity signature
            Signature entitySignature = new Signature()
            {
                visibleSignature = BuildVisibleSignature(signatureParameters.page,
                                                         5,
                                                         signatureParameters.y,
                                                         5,
                                                         5,
                                                         _Scenario.EntityLayout)
            };

            //Personal signature
            IList<PersonalSignature> personalSignatures = new List<PersonalSignature>();

            //Signature USER-ADVISER
            PersonalSignature personalSignature = new PersonalSignature()
            {
                user = "******",
                signatureLabel = "ADVISER-SIGNATURE",
                visibleSignature = BuildVisibleSignature(signatureParameters.page,
                                                         signatureParameters.x_adviser,
                                                         signatureParameters.y,
                                                         signatureParameters.width,
                                                         signatureParameters.height,
                                                         _Scenario.PersonalLayout)
            };

            personalSignatures.Add(personalSignature);

            //Signature USER-CUSTOMER
            PersonalSignature personalSignature1 = new PersonalSignature()
            {
                user = "******",
                signatureLabel = "CUSTOMER-SIGNATURE",
                visibleSignature = BuildVisibleSignature(signatureParameters.page,
                                                         signatureParameters.x_customer,
                                                         signatureParameters.y,
                                                         signatureParameters.width,
                                                         signatureParameters.height,
                                                         _Scenario.PersonalLayout)
            };

            personalSignatures.Add(personalSignature1);

            Signatures signatures = new Signatures()
            {
                entity = entitySignature,
                personal = personalSignatures.ToArray()
            };

            return signatures;
        }
예제 #20
0
        protected override async Task <APIResultCodes> AuthorizeImplAsync <T>(DagSystem sys, T tblock)
        {
            if (!(tblock is ServiceBlock))
            {
                return(APIResultCodes.InvalidBlockType);
            }

            var block = tblock as ServiceBlock;

            var prevBlock = await sys.Storage.FindBlockByHashAsync(block.PreviousHash);

            // service specifice feature
            if (block.FeeTicker != LyraGlobal.OFFICIALTICKERCODE)
            {
                return(APIResultCodes.InvalidFeeTicker);
            }

            var board = await sys.Consensus.Ask <BillBoard>(new AskForBillboard());

            if (prevBlock != null) // only if this is not very first service block
            {
                // verify fees
                var allConsBlocks = await sys.Storage.GetConsolidationBlocksAsync(prevBlock.Hash);

                var feesGened = allConsBlocks.Sum(a => a.totalFees);

                if (block.FeesGenerated != feesGened)
                {
                    return(APIResultCodes.InvalidServiceBlockTotalFees);
                }

                var signAgainst = prevBlock?.Hash ?? ProtocolSettings.Default.StandbyValidators[0];

                foreach (var voter in board.AllVoters)
                {
                    var node = board.ActiveNodes.FirstOrDefault(a => a.AccountID == voter);
                    if (node != null && Signatures.VerifyAccountSignature(signAgainst, node.AccountID, node.AuthorizerSignature))
                    {
                        if (!block.Authorizers.ContainsKey(voter))
                        {
                            return(APIResultCodes.InvalidAuthorizerInServiceBlock);
                        }
                    }
                }

                if (block.Authorizers.Keys.Any(a => !board.AllVoters.Contains(a)))
                {
                    return(APIResultCodes.InvalidAuthorizerInServiceBlock);
                }

                var myscvb = await sys.Consensus.Ask <ServiceBlock>(new AskForServiceBlock());

                if (!myscvb.AuthCompare(block))
                {
                    Console.WriteLine($"\nCompare service block, myscvb vs block");
                    Console.WriteLine(ObjectDumper.Dump(myscvb));
                    Console.WriteLine(ObjectDumper.Dump(block));
                    return(APIResultCodes.BlockCompareFailed);
                }
            }
            else // svc gensis
            {
                if (block.Authorizers.Count < LyraGlobal.MINIMUM_AUTHORIZERS)
                {
                    return(APIResultCodes.InvalidAuthorizerCount);
                }

                var signAgainst = ProtocolSettings.Default.StandbyValidators[0];
                foreach (var pn in ProtocolSettings.Default.StandbyValidators)
                {
                    if (!board.ActiveNodes.Any(a => a.AccountID == pn))
                    {
                        return(APIResultCodes.InvalidAuthorizerInServiceBlock);
                    }

                    if (!Signatures.VerifyAccountSignature(signAgainst, pn, block.Authorizers[pn]))
                    {
                        return(APIResultCodes.InvalidAuthorizerSignatureInServiceBlock);
                    }
                }
            }

            return(await Lyra.Shared.StopWatcher.TrackAsync(() => base.AuthorizeImplAsync(sys, tblock), "ServiceAuthorizer->BaseAuthorizer"));
        }
예제 #21
0
        public static void Initialize(CashmoreAppContext context)
        {
            //context.Database.EnsureCreated();

            // Look for any Entities.
            if (context.Entities.Any())
            {
                return;   // DB has been seeded
            }

            // Add the Entities
            var entities = new Entity[]
            {
                // Hospital
                new Entity {
                    EntityName    = "Your Hospital", EntityAddress1 = "123 Main Street", EntityAddress2 = "", EntityCity = "Big City", EntityState = "IL", EntityZipcode = "61104",
                    EntityCountry = "USA", EntityPhoneNumber = "8881231234", EntityType = EntityTypes.Hospital
                },
                // Vender1
                new Entity {
                    EntityName    = "Vendor 1", EntityAddress1 = "12345 1st Street", EntityAddress2 = "", EntityCity = "Big City", EntityState = "IL", EntityZipcode = "61114",
                    EntityCountry = "USA", EntityPhoneNumber = "8888888888", EntityType = EntityTypes.Vendor
                },
                // Vendor2
                new Entity {
                    EntityName    = "Vendor 2", EntityAddress1 = "432 West Street", EntityAddress2 = "Suite 103", EntityCity = "Medium City", EntityState = "WI", EntityZipcode = "55555",
                    EntityCountry = "USA", EntityPhoneNumber = "7777777777", EntityType = EntityTypes.Vendor
                },
                // Vendor3
                new Entity {
                    EntityName    = "Vendor 3", EntityAddress1 = "444 4th Street", EntityAddress2 = "Suite 444", EntityCity = "Large City", EntityState = "CA", EntityZipcode = "11111",
                    EntityCountry = "USA", EntityPhoneNumber = "5555555555", EntityType = EntityTypes.Vendor
                }
            };

            foreach (Entity e in entities)
            {
                context.Entities.Add(e);
            }
            context.SaveChanges();

            //Add Users
            // Load the entities for easier access when mapping users
            var hospital    = entities.Single(e => e.EntityName == "Your Hospital");
            var vendorOne   = entities.Single(e => e.EntityName == "Vendor 1");
            var vendorTwo   = entities.Single(e => e.EntityName == "Vendor 2");
            var vendorThree = entities.Single(e => e.EntityName == "Vendor 3");

            var users = new User[]
            {
                new User {
                    UserFirstName = "Leader 1", UserLastName = "Hospital", UserEmail = "*****@*****.**", UserPassword = "******", UserAccessLevel = Access.FullAccess,
                    EntityID      = hospital.EntityID
                },
                new User {
                    UserFirstName = "Leader 2", UserLastName = "Hospital", UserEmail = "*****@*****.**", UserPassword = "******", UserAccessLevel = Access.FullAccess,
                    EntityID      = hospital.EntityID
                },
                new User {
                    UserFirstName = "User 1", UserLastName = "Hospital", UserEmail = "*****@*****.**", UserPassword = "******", UserAccessLevel = Access.ReadOnly,
                    EntityID      = hospital.EntityID
                },
                new User {
                    UserFirstName = "Leader 1", UserLastName = "Vendor 1", UserEmail = "*****@*****.**", UserPassword = "******", UserAccessLevel = Access.FullAccess,
                    EntityID      = vendorOne.EntityID
                },
                new User {
                    UserFirstName = "Leader 1", UserLastName = "Vendor 2", UserEmail = "*****@*****.**", UserPassword = "******", UserAccessLevel = Access.FullAccess,
                    EntityID      = vendorTwo.EntityID
                },
                new User {
                    UserFirstName = "Leader 1", UserLastName = "Vendor 3", UserEmail = "*****@*****.**", UserPassword = "******", UserAccessLevel = Access.FullAccess,
                    EntityID      = vendorThree.EntityID
                }
            };

            foreach (User u in users)
            {
                context.Users.Add(u);
            }
            context.SaveChanges();


            // Map Users to Entities
            // Hospital
            // var hospital = entities.Single( e => e.EntityName == "Your Hospital");
            // var hospitalUsers = users.Where(u => u.UserLastName == "Hospital");
            // foreach(User u in hospitalUsers)
            // {
            //     hospital.EntityUsers.Add(u);
            // }
            // context.SaveChanges();
            // // Vendor 1
            // var vendorOne = entities.Single( e => e.EntityName == "Vendor 1");
            // var vendorOneUsers = users.Single(u => u.UserLastName == "Vendor 1");
            // vendorOne.EntityUsers.Add(vendorOneUsers);
            // context.SaveChanges();
            // // Vendor 2
            // var vendorTwo = entities.Single( e => e.EntityName == "Vendor 2");
            // var vendorTwoUsers = users.Single(u => u.UserLastName == "Vendor 2");
            // vendorTwo.EntityUsers.Add(vendorTwoUsers);
            // context.SaveChanges();
            // // Vendor 1
            // var vendorThree = entities.Single( e => e.EntityName == "Vendor 3");
            // var vendorThreeUsers = users.Single(u => u.UserLastName == "Vendor 3");
            // vendorThree.EntityUsers.Add(vendorThreeUsers);
            // context.SaveChanges();


            // Add some Contracts
            var contracts = new Contract[]
            {
                // Fully Completed Contract
                new Contract {
                    ContractProductLine = "Ultrasound U9", ContractPurchaseOrder = "C123782", ContractStatus = "Active", ContractStartDate = DateTime.Parse("2017-03-02"),
                    ContractEndDate     = DateTime.Parse("2018-03-01"), ContractValue = 60000m
                },
                // One Signature Contract
                new Contract {
                    ContractProductLine = "Medical Supplies", ContractPurchaseOrder = "N/A", ContractStatus = "Active", ContractStartDate = DateTime.Parse("2012-11-01"),
                    ContractEndDate     = DateTime.Parse("2017-10-30"), ContractValue = 50000000m
                },
                // No Signatures Contract
                new Contract {
                    ContractProductLine = "MA for Ultrasound 9", ContractPurchaseOrder = "987621", ContractStatus = "Active", ContractStartDate = DateTime.Parse("2018-03-01"),
                    ContractEndDate     = DateTime.Parse("2021-02-28"), ContractValue = 30000m
                }
            };

            foreach (Contract c in contracts)
            {
                context.Contracts.Add(c);
            }
            context.SaveChanges();


            // Add Entities to Contracts
            var contractOne   = contracts.Single(c => c.ContractProductLine == "Ultrasound U9");
            var contractTwo   = contracts.Single(c => c.ContractProductLine == "Medical Supplies");
            var contractThree = contracts.Single(c => c.ContractProductLine == "MA for Ultrasound 9");

            var entityContracts = new EntityToContract[]
            {
                // Contract 1
                new EntityToContract {
                    EntityID = hospital.EntityID, ContractID = contractOne.ContractID
                },
                new EntityToContract {
                    EntityID = vendorOne.EntityID, ContractID = contractOne.ContractID
                },
                // Contract 2
                new EntityToContract {
                    EntityID = hospital.EntityID, ContractID = contractTwo.ContractID
                },
                new EntityToContract {
                    EntityID = vendorTwo.EntityID, ContractID = contractTwo.ContractID
                },
                // Contract 3
                new EntityToContract {
                    EntityID = hospital.EntityID, ContractID = contractThree.ContractID
                },
                new EntityToContract {
                    EntityID = vendorOne.EntityID, ContractID = contractThree.ContractID
                }
            };

            foreach (EntityToContract etc in entityContracts)
            {
                context.EntityContracts.Add(etc);
            }
            context.SaveChanges();
            // var contractOne = contracts.Single( c => c.ContractProductLine == "Ultrasound U9");
            // contractOne.ContractEntities.Add(hospital);
            // contractOne.ContractEntities.Add(vendorOne);

            // var contractTwo = contracts.Single( c => c.ContractProductLine == "Medical Supplies");
            // contractTwo.ContractEntities.Add(hospital);
            // contractTwo.ContractEntities.Add(vendorTwo);

            // var contractThree = contracts.Single( c => c.ContractProductLine == "MA for Ultrasound 9");
            // contractThree.ContractEntities.Add(hospital);
            // contractThree.ContractEntities.Add(vendorOne);

            // context.SaveChanges();


            // Add Signatures to Contracts
            // Grab the leaders to map to signatures
            var hospitalUsers    = users.Where(u => u.UserLastName == "Hospital");
            var hospitalLeader   = hospitalUsers.Single(u => u.UserFirstName == "Leader 1");
            var vendorOneUsers   = users.Single(u => u.UserLastName == "Vendor 1");
            var vendorTwoUsers   = users.Single(u => u.UserLastName == "Vendor 2");
            var vendorThreeUsers = users.Single(u => u.UserLastName == "Vendor 3");

            // Contract One has everything signed
            var contractOneSignatures = new Signatures[]
            {
                new Signatures {
                    ContractID = contractOne.ContractID, ContractType = ContractTypes.CaptialContract, HospitalSignature = hospitalLeader, VendorSignature = vendorOneUsers
                },
                new Signatures {
                    ContractID = contractOne.ContractID, ContractType = ContractTypes.MaintenanceAgreementContract, HospitalSignature = hospitalLeader, VendorSignature = vendorOneUsers
                },
                new Signatures {
                    ContractID = contractOne.ContractID, ContractType = ContractTypes.NetworkAccessContract, HospitalSignature = hospitalLeader, VendorSignature = vendorOneUsers
                },
                new Signatures {
                    ContractID = contractOne.ContractID, ContractType = ContractTypes.BAAContract, HospitalSignature = hospitalLeader, VendorSignature = vendorOneUsers
                },
                new Signatures {
                    ContractID = contractOne.ContractID, ContractType = ContractTypes.SecurityRiderContract, HospitalSignature = hospitalLeader, VendorSignature = vendorOneUsers
                },
                new Signatures {
                    ContractID = contractOne.ContractID, ContractType = ContractTypes.SecurityAssessmentContract, HospitalSignature = hospitalLeader, VendorSignature = vendorOneUsers
                }
            };

            foreach (Signatures s in contractOneSignatures)
            {
                context.Signatures.Add(s);
            }
            context.SaveChanges();

            // Contract 2 has everything signed from the hospital side
            var contractTwoSignatures = new Signatures[]
            {
                new Signatures {
                    ContractID = contractTwo.ContractID, ContractType = ContractTypes.SupplyContract, HospitalSignature = hospitalLeader
                },
                new Signatures {
                    ContractID = contractTwo.ContractID, ContractType = ContractTypes.MinorEquipmentContract, HospitalSignature = hospitalLeader
                },
                new Signatures {
                    ContractID = contractTwo.ContractID, ContractType = ContractTypes.ProductUsageContract, HospitalSignature = hospitalLeader
                }
            };

            foreach (Signatures s in contractTwoSignatures)
            {
                context.Signatures.Add(s);
            }
            context.SaveChanges();

            // Contract 3 we will add signatures as a test, so no signatures are needed
        }
예제 #22
0
        public static Packet DecodePacket(DataReader reader)
        {
            reader.ByteOrder = ByteOrder.BigEndian;
            int signature       = reader.ReadByte();
            int remainingLength = DecodeRemainingLength(reader);

            if (Signatures.IsPublish(signature))
            {
                var qualityOfService =
                    (QualityOfService)((signature >> 1) &
                                       0x3);  // take bits #1 and #2 ONLY and convert them into QoS value
                if (qualityOfService == QualityOfService.Reserved)
                {
                    throw new Exception(
                              $"Unexpected QoS value of {(int)qualityOfService} for {PacketType.PUBLISH} packet.");
                }

                bool duplicate = (signature & 0x8) == 0x8; // test bit#3
                bool retain    = (signature & 0x1) != 0;   // test bit#0
                var  packet    = new PublishPacket(qualityOfService, duplicate, retain);
                DecodePublishPacket(reader, packet, ref remainingLength);
                return(packet);
            }

            switch (signature & 240)  // We don't care about flags for these packets
            {
            // case Signatures.Subscribe & 240:
            //     var subscribePacket = new SubscribePacket();
            //     DecodePacketIdVariableHeader(reader, subscribePacket, ref remainingLength);
            //     DecodeSubscribePayload(buffer, subscribePacket, ref remainingLength);
            //     return subscribePacket;
            case Signatures.Connect:
                var connectPacket = new ConnectPacket();
                DecodeConnectPacket(reader, connectPacket, ref remainingLength);
                return(connectPacket);

            case Signatures.PubAck:
                var pubAckPacket = new PubAckPacket();
                DecodePacketIdVariableHeader(reader, pubAckPacket, ref remainingLength);
                return(pubAckPacket);

            case Signatures.ConnAck:
                var connAckPacket = new FbnsConnAckPacket();
                DecodeConnAckPacket(reader, connAckPacket, ref remainingLength);
                return(connAckPacket);

            case Signatures.SubAck:
                var subAckPacket = new SubAckPacket();
                DecodePacketIdVariableHeader(reader, subAckPacket, ref remainingLength);
                DecodeSubAckPayload(reader, subAckPacket, ref remainingLength);
                return(subAckPacket);

            case Signatures.UnsubAck:
                var unsubAckPacket = new UnsubAckPacket();
                DecodePacketIdVariableHeader(reader, unsubAckPacket, ref remainingLength);
                return(unsubAckPacket);

            case Signatures.PingResp:
                return(PingRespPacket.Instance);

            default:
                throw new Exception($"Packet type {signature} not supported");
            }
        }
예제 #23
0
        static void Main(string[] args)
        {
            InitIO();

            var n = int.Parse(Console.ReadLine());

            Console.Error.WriteLine("Input files: {0}", n);

            var graph      = new Graph <string>();
            var comparer   = new CodeComparer(new CodeAnalyzerBuilder());
            var signatures = new Signatures();
            var files      = new string[n];

            for (var i = 0; i < n; i++)
            {
                files[i] = Console.ReadLine();

                var language = Path.GetExtension(files[i]);
                var code     = File.ReadAllText(files[i]);
                code = signatures.FormatCode(code);

                var codeAnalyzer = new SuffixTreeCodeAnalyzer(language, code);

                graph.AddVertex(files[i]);
                comparer.Register(files[i], language, code);

                if ((i + 1) % 100 == 0)
                {
                    OnProgress("Parsed: ", i + 1, n);
                }
            }

            var maximum  = (long)(n) * (long)(n - 1) / 2;
            var progress = (long)0;

            OnProgress("Compared: ", progress, maximum);
            for (var i = 0; i < n; i++)
            {
                for (var j = i + 1; j < n; j++)
                {
                    if (++progress % 10000 == 0)
                    {
                        OnProgress(progress, maximum);
                    }

                    if (files[i].Contains('-') && files[j].Contains('-'))
                    {
                        var id1 = files[i].Substring(0, files[i].IndexOf('-'));
                        var id2 = files[j].Substring(0, files[j].IndexOf('-'));

                        if (id1 == id2)
                        {
                            continue;
                        }
                    }

                    decimal compare = comparer.Compare(files[i], files[j]);


                    if (compare > 0.33M)
                    {
                        Console.Error.WriteLine("{0} | {1} -> {2:0.00}%", files[i], files[j], compare * 100);
                        graph.AddEdge(files[i], files[j]);
                    }
                }
            }

            OnProgress(progress, maximum);

            var res = from c in graph.GetConnectedComponents()
                      where c.Count >= 2
                      select c;

            Console.WriteLine(res.Count());
            Console.Error.WriteLine(res.Count());
            foreach (var g in res)
            {
                foreach (var file in g.Verticies)
                {
                    Console.Write(file + " ");
                    Console.Error.Write(file + " ");
                }
                Console.WriteLine();
                Console.Error.WriteLine();
            }
            Console.Out.Dispose();
        }
예제 #24
0
        public async Task ExecuteAsync(object?parameter = null, CancellationToken cancellation = default)
        {
            var repositoryStatus = repository.RetrieveStatus();

            var localBranch  = repository.Head;
            var targetBranch = repository.Head.TrackedBranch ?? repository.Head;

            var dialog = new PullDialog(
                targetBranch.RemoteName ?? repository.GetDefaultRemoteName(),
                targetBranch.GetName(),
                showStashWarning: repositoryStatus.IsDirty,
                trackRemoteBranch: false,
                remotes: repository.GetRemoteNames(),
                branches: repository.GetBranchNames());

            if (mainThread.Invoke(() => dialog.ShowDialog()) == true && !string.IsNullOrEmpty(dialog.Branch))
            {
                var targetBranchFriendlyName = string.IsNullOrEmpty(dialog.Remote) ?
                                               dialog.Branch : $"{dialog.Remote}/{dialog.Branch}";

                targetBranch = repository.Branches.FirstOrDefault(x => x.FriendlyName == targetBranchFriendlyName);

                if (targetBranch == null)
                {
                    throw new InvalidOperationException(string.Format("Branch {0} not found", targetBranchFriendlyName));
                }

                eventStream.Push(Status.Start("Pull {0} {1}", targetBranchFriendlyName, dialog.IsFastForward ? "With Fast Fordward" : string.Empty));

                var stash       = default(Stash);
                var mergeResult = default(MergeResult);
                var stashResult = default(StashApplyStatus);

                // 1. Fetch
                if (targetBranch.IsRemote)
                {
                    TryFetch(targetBranch);
                }

                // 2. Stash (optional, if the repo is dirty) and Merge
                try
                {
                    if (repositoryStatus.IsDirty)
                    {
                        stash = repository.Stashes.Add(Signatures.GetStashSignature(), StashModifiers.IncludeUntracked);
                    }

                    mergeResult = Merge(targetBranch, dialog.IsFastForward);
                }
                finally
                {
                    if (stash != null && repository.Stashes.Contains(stash) && !repository.RetrieveStatus().IsDirty)
                    {
                        stashResult = repository.Stashes.Pop(repository.Stashes.ToList().IndexOf(stash));
                    }
                }

                // 3. Resolve conflicts
                if (mergeResult?.Status == MergeStatus.Conflicts)
                {
                    await commandService.RunAsync("ResolveConflicts");
                }

                // 4. Track
                if (dialog.TrackRemoteBranch)
                {
                    localBranch.Track(repository, targetBranch);
                }

                // 5. Update submodules
                if (dialog.UpdateSubmodules)
                {
                    eventStream.Push(Status.Create(0.8f, "Updating submodules..."));
                    repository.UpdateSubmodules(eventStream: eventStream);
                }

                eventStream.Push(Status.Finish(mergeResult.Status.ToString()));

                mainThread.Invoke(() => view.Refresh());
            }
        }
        public void LoadDummyData()
        {
            #region user dummy data
            Users.Add(new User()
            {
                Id       = 1,
                Name     = "Admin",
                Email    = "*****@*****.**",
                Jabatan  = "Komisaris",
                Password = PasswordHash.GetHash("12345678"),
                Role     = EUserRole.Admin
            });
            Users.Add(new User()
            {
                Id       = 2,
                Name     = "AR",
                Email    = "*****@*****.**",
                Jabatan  = "Management Resiko",
                Password = PasswordHash.GetHash("12345678"),
                Role     = EUserRole.AR
            });
            Users.Add(new User()
            {
                Id       = 3,
                Name     = "User",
                Email    = "*****@*****.**",
                Jabatan  = "Karyawan",
                Password = PasswordHash.GetHash("12345678"),
                Role     = EUserRole.User
            });
            Users.Add(new User()
            {
                Id       = 4,
                Name     = "FBS",
                Email    = "*****@*****.**",
                Jabatan  = "Keuangan",
                Password = PasswordHash.GetHash("12345678"),
                Role     = EUserRole.FBS
            });
            #endregion

            #region customer dummy data
            Customers.Add(new Customer()
            {
                Id         = 1,
                CustomerNo = "1236969",
                Name       = "PT Kera Sakti",
                Email      = "*****@*****.**",
                Address    = "Gunung kayangan",
                NPWP       = "01010169"
            });
            Customers.Add(new Customer()
            {
                Id         = 2,
                CustomerNo = "4616111",
                Name       = "Cv Kamehameha Batam",
                Email      = "*****@*****.**",
                Address    = "Pulau roshi",
                NPWP       = "222333444"
            });
            Customers.Add(new Customer()
            {
                Id         = 3,
                CustomerNo = "3456789",
                Name       = "PT Santai Menyantai",
                Email      = "*****@*****.**",
                Address    = "Jalan malas",
                NPWP       = "55667788"
            });
            Customers.Add(new Customer()
            {
                Id         = 4,
                CustomerNo = "3456789",
                Name       = "PT Ninja Gadungan",
                Email      = "*****@*****.**",
                Address    = "Konohahaha",
                NPWP       = "777888999"
            });
            #endregion

            #region product dummy data
            Products.Add(new Product()
            {
                Id            = 1,
                MaterialNo    = "001",
                MaterialName  = "Premium",
                MaterialGroup = "001"
            });
            Products.Add(new Product()
            {
                Id            = 2,
                MaterialNo    = "002",
                MaterialName  = "Pertalite",
                MaterialGroup = "002"
            });
            Products.Add(new Product()
            {
                Id            = 3,
                MaterialNo    = "003",
                MaterialName  = "Solar",
                MaterialGroup = "003"
            });
            Products.Add(new Product()
            {
                Id            = 4,
                MaterialNo    = "004",
                MaterialName  = "Pertamax",
                MaterialGroup = "004"
            });
            #endregion

            #region signature dummy data
            Signatures.Add(new Signature()
            {
                Id           = 1,
                Name1        = "Basuki cahaya purnama",
                Name2        = "Eric Thoir",
                Position1    = "Komisaris Utama",
                Position2    = "Menteri BUMN",
                DocumentType = "CA"
            });
            Signatures.Add(new Signature()
            {
                Id           = 2,
                Name1        = "Goku",
                Name2        = "Vegeta",
                Position1    = "Earth Saiyan",
                Position2    = "Prince Saiyan",
                DocumentType = "CA"
            });
            Signatures.Add(new Signature()
            {
                Id           = 3,
                Name1        = "Ramen",
                Name2        = "Burger",
                Position1    = "Japanese Noodle",
                Position2    = "USA Sandwich",
                DocumentType = "CA"
            });
            Signatures.Add(new Signature()
            {
                Id           = 4,
                Name1        = "PUBG",
                Name2        = "Mobile Legend",
                Position1    = "Battle Royale",
                Position2    = "Moba",
                DocumentType = "CA"
            });
            #endregion

            #region credit approval dummy data
            CreditApprovals.Add(new CreditApproval()
            {
                Id               = 1,
                TicketNumber     = "44667788",
                MailNumber       = "1122334455",
                CustomerId       = 3,
                TempoStart       = Convert.ToDateTime("01/12/2019"),
                TempoEnd         = Convert.ToDateTime("05/05/2020"),
                LongTempo        = "Perbulan 1 kali",
                Volume           = "2 Liter",
                Units            = "Per Kg",
                PeriodeVolume    = "Perbulan Volume",
                SubmissionPeriod = "Kapan Saja",
                TransactionValue = "Rp 2.000.000",
                CreditLimit      = "Rp 2.500.000",
                Payment          = "Bank Indonesia",
                Guarantee        = "BPOM",
                Status           = EStatusCredit.DraftUser,
                FlagRead         = true,
                FlagFine         = true,
                CreatedBy        = 1,
                Currency         = "Rp",
                TransactionValueEstimatedPeriod = "Perbulan Pengeluaran",
                TrCaActionNote      = new List <TrCaActionNote>(),
                TrCaProducts        = new List <TrCaProduct>(),
                TrCaNotes           = new List <TrCaNote>(),
                CaCustomerDetails   = new List <CaCustomerDetail>(),
                QuantitativeAspects = new List <QuantitativeAspect>(),
                CreditScorings      = new List <CreditScoring>(),
                User = new User()
                {
                    Id       = 1,
                    Name     = "Admin",
                    Email    = "*****@*****.**",
                    Jabatan  = "Komisaris",
                    Password = PasswordHash.GetHash("12345678"),
                    Role     = EUserRole.Admin
                }
            });
            CreditApprovals.Add(new CreditApproval()
            {
                Id               = 2,
                TicketNumber     = "44667788",
                MailNumber       = "1122334455",
                CustomerId       = 2,
                TempoStart       = Convert.ToDateTime("01/12/2019"),
                TempoEnd         = Convert.ToDateTime("05/05/2020"),
                LongTempo        = "Perbulan 1 kali",
                Volume           = "2 Liter",
                Units            = "Per Kg",
                PeriodeVolume    = "Perbulan Volume",
                SubmissionPeriod = "Kapan Saja",
                TransactionValue = "Rp 2.000.000",
                CreditLimit      = "Rp 2.500.000",
                Payment          = "Bank Indonesia",
                Guarantee        = "BPOM",
                Status           = EStatusCredit.AR,
                FlagRead         = true,
                FlagFine         = true,
                CreatedBy        = 1,
                Currency         = "Rp",
                TransactionValueEstimatedPeriod = "Perbulan Pengeluaran",
                TrCaActionNote      = new List <TrCaActionNote>(),
                TrCaProducts        = new List <TrCaProduct>(),
                TrCaNotes           = new List <TrCaNote>(),
                CaCustomerDetails   = new List <CaCustomerDetail>(),
                QuantitativeAspects = new List <QuantitativeAspect>(),
                CreditScorings      = new List <CreditScoring>(),
                User = new User()
                {
                    Id       = 1,
                    Name     = "Admin",
                    Email    = "*****@*****.**",
                    Jabatan  = "Komisaris",
                    Password = PasswordHash.GetHash("12345678"),
                    Role     = EUserRole.Admin
                }
            });
            CreditApprovals.Add(new CreditApproval()
            {
                Id               = 3,
                TicketNumber     = "44667788",
                MailNumber       = "1122334455",
                CustomerId       = 1,
                TempoStart       = Convert.ToDateTime("01/12/2019"),
                TempoEnd         = Convert.ToDateTime("05/05/2020"),
                LongTempo        = "Perbulan 1 kali",
                Volume           = "2 Liter",
                Units            = "Per Kg",
                PeriodeVolume    = "Perbulan Volume",
                SubmissionPeriod = "Kapan Saja",
                TransactionValue = "Rp 2.000.000",
                CreditLimit      = "Rp 2.500.000",
                Payment          = "Bank Indonesia",
                Guarantee        = "BPOM",
                Status           = EStatusCredit.CashBank,
                FlagRead         = true,
                FlagFine         = true,
                CreatedBy        = 1,
                Currency         = "Rp",
                TransactionValueEstimatedPeriod = "Perbulan Pengeluaran",
                TrCaActionNote      = new List <TrCaActionNote>(),
                TrCaProducts        = new List <TrCaProduct>(),
                TrCaNotes           = new List <TrCaNote>(),
                CaCustomerDetails   = new List <CaCustomerDetail>(),
                QuantitativeAspects = new List <QuantitativeAspect>(),
                CreditScorings      = new List <CreditScoring>(),
                User = new User()
                {
                    Id       = 1,
                    Name     = "Admin",
                    Email    = "*****@*****.**",
                    Jabatan  = "Komisaris",
                    Password = PasswordHash.GetHash("12345678"),
                    Role     = EUserRole.Admin
                }
            });
            CreditApprovals.Add(new CreditApproval()
            {
                Id               = 4,
                TicketNumber     = "44667788",
                MailNumber       = "1122334455",
                CustomerId       = 4,
                TempoStart       = Convert.ToDateTime("01/12/2019"),
                TempoEnd         = Convert.ToDateTime("05/05/2020"),
                LongTempo        = "Perbulan 1 kali",
                Volume           = "2 Liter",
                Units            = "Per Kg",
                PeriodeVolume    = "Perbulan Volume",
                SubmissionPeriod = "Kapan Saja",
                TransactionValue = "Rp 2.000.000",
                CreditLimit      = "Rp 2.500.000",
                Payment          = "Bank Indonesia",
                Guarantee        = "BPOM",
                Status           = EStatusCredit.FBS,
                FlagRead         = true,
                FlagFine         = true,
                CreatedBy        = 1,
                Currency         = "Rp",
                TransactionValueEstimatedPeriod = "Perbulan Pengeluaran",
                TrCaActionNote      = new List <TrCaActionNote>(),
                TrCaProducts        = new List <TrCaProduct>(),
                TrCaNotes           = new List <TrCaNote>(),
                CaCustomerDetails   = new List <CaCustomerDetail>(),
                QuantitativeAspects = new List <QuantitativeAspect>(),
                CreditScorings      = new List <CreditScoring>(),
                User = new User()
                {
                    Id       = 1,
                    Name     = "Admin",
                    Email    = "*****@*****.**",
                    Jabatan  = "Komisaris",
                    Password = PasswordHash.GetHash("12345678"),
                    Role     = EUserRole.Admin
                }
            });
            CreditApprovals.Add(new CreditApproval()
            {
                Id               = 5,
                TicketNumber     = "44667788",
                MailNumber       = "1122334455",
                CustomerId       = 2,
                TempoStart       = Convert.ToDateTime("01/12/2019"),
                TempoEnd         = Convert.ToDateTime("05/05/2020"),
                LongTempo        = "Perbulan 1 kali",
                Volume           = "2 Liter",
                Units            = "Per Kg",
                PeriodeVolume    = "Perbulan Volume",
                SubmissionPeriod = "Kapan Saja",
                TransactionValue = "Rp 2.000.000",
                CreditLimit      = "Rp 2.500.000",
                Payment          = "Bank Indonesia",
                Guarantee        = "BPOM",
                Status           = EStatusCredit.ManagementRisk,
                FlagRead         = true,
                FlagFine         = true,
                CreatedBy        = 1,
                Currency         = "Rp",
                TransactionValueEstimatedPeriod = "Perbulan Pengeluaran",
                TrCaActionNote      = new List <TrCaActionNote>(),
                TrCaProducts        = new List <TrCaProduct>(),
                TrCaNotes           = new List <TrCaNote>(),
                CaCustomerDetails   = new List <CaCustomerDetail>(),
                QuantitativeAspects = new List <QuantitativeAspect>(),
                CreditScorings      = new List <CreditScoring>(),
                User = new User()
                {
                    Id       = 1,
                    Name     = "Admin",
                    Email    = "*****@*****.**",
                    Jabatan  = "Komisaris",
                    Password = PasswordHash.GetHash("12345678"),
                    Role     = EUserRole.Admin
                }
            });
            CreditApprovals.Add(new CreditApproval()
            {
                Id               = 6,
                TicketNumber     = "44667788",
                MailNumber       = "1122334455",
                CustomerId       = 1,
                TempoStart       = Convert.ToDateTime("01/12/2019"),
                TempoEnd         = Convert.ToDateTime("05/05/2020"),
                LongTempo        = "Perbulan 1 kali",
                Volume           = "2 Liter",
                Units            = "Per Kg",
                PeriodeVolume    = "Perbulan Volume",
                SubmissionPeriod = "Kapan Saja",
                TransactionValue = "Rp 2.000.000",
                CreditLimit      = "Rp 2.500.000",
                Payment          = "Bank Indonesia",
                Guarantee        = "BPOM",
                Status           = EStatusCredit.KomiteCredit,
                FlagRead         = true,
                FlagFine         = true,
                CreatedBy        = 1,
                Currency         = "Rp",
                TransactionValueEstimatedPeriod = "Perbulan Pengeluaran",
                TrCaActionNote      = new List <TrCaActionNote>(),
                TrCaProducts        = new List <TrCaProduct>(),
                TrCaNotes           = new List <TrCaNote>(),
                CaCustomerDetails   = new List <CaCustomerDetail>(),
                QuantitativeAspects = new List <QuantitativeAspect>(),
                CreditScorings      = new List <CreditScoring>(),
                User = new User()
                {
                    Id       = 1,
                    Name     = "Admin",
                    Email    = "*****@*****.**",
                    Jabatan  = "Komisaris",
                    Password = PasswordHash.GetHash("12345678"),
                    Role     = EUserRole.Admin
                }
            });
            #endregion

            #region tr ca note dummy data
            TrCaNotes.Add(new TrCaNote()
            {
                Id = 1,
                CreditApprovalId = 1,
                TanggalNota      = Convert.ToDateTime("12/12/2019"),
                Perihal          = "Pesan Dari FBS",
                Isi       = "Data ini valid",
                CreatedBy = "Admin",
                CreatedAt = DateTime.Now,
                UpdatedAt = DateTime.Now
            });
            TrCaNotes.Add(new TrCaNote()
            {
                Id = 2,
                CreditApprovalId = 2,
                TanggalNota      = Convert.ToDateTime("12/12/2019"),
                Perihal          = "Pesan Dari FBS",
                Isi       = "Data ini valid",
                CreatedBy = "Admin",
                CreatedAt = DateTime.Now,
                UpdatedAt = DateTime.Now
            });
            TrCaNotes.Add(new TrCaNote()
            {
                Id = 3,
                CreditApprovalId = 3,
                TanggalNota      = Convert.ToDateTime("12/12/2019"),
                Perihal          = "Pesan Dari FBS",
                Isi       = "Data ini valid",
                CreatedBy = "Admin",
                CreatedAt = DateTime.Now,
                UpdatedAt = DateTime.Now
            });
            #endregion
        }
예제 #26
0
 public void XorTwoBooleans_Execute_CorrectResultValue()
 {
     TestPureBinaryBooleanOperation(Signatures.DefinePureBinaryFunction("Xor", NITypes.Boolean, NITypes.Boolean), true, false, true);
 }
예제 #27
0
        public override async Task <TransactionBlock> BrokerOpsAsync(DagSystem sys, SendTransferBlock send)
        {
            var blocks = await sys.Storage.FindBlocksByRelatedTxAsync(send.Hash);

            if (blocks.Any(a => a is PoolWithdrawBlock))
            {
                return(null);
            }

            var lsb = await sys.Storage.GetLastServiceBlockAsync();

            var recvBlock = await sys.Storage.FindBlockBySourceHashAsync(send.Hash);

            var poolGenesis = sys.Storage.GetPoolByID(send.Tags["poolid"]);
            var poolId      = poolGenesis.AccountID;

            PoolWithdrawBlock withdrawBlock = new PoolWithdrawBlock
            {
                AccountID            = poolId,
                ServiceHash          = lsb.Hash,
                DestinationAccountId = send.AccountID,
                Balances             = new Dictionary <string, long>(),
                Tags      = null,
                Fee       = 0,
                FeeCode   = LyraGlobal.OFFICIALTICKERCODE,
                FeeType   = AuthorizationFeeTypes.NoFee,
                RelatedTx = send.Hash
            };

            var sendBlock = await sys.Storage.FindBlockByHashAsync(recvBlock.SourceHash) as SendTransferBlock;

            withdrawBlock.AddTag(Block.MANAGEDTAG, "");   // value is always ignored

            var poolGenesisBlock = await sys.Storage.FindFirstBlockAsync(poolId) as PoolGenesisBlock;

            var poolLatestBlock = await sys.Storage.FindLatestBlockAsync(poolId) as TransactionBlock;

            var curBalance = poolLatestBlock.Balances.ToDecimalDict();
            var curShares  = (poolLatestBlock as IPool).Shares.ToRitoDecimalDict();

            var nextBalance = poolLatestBlock.Balances.ToDecimalDict();
            var nextShares  = (poolLatestBlock as IPool).Shares.ToRitoDecimalDict();

            var usersShare    = curShares[send.AccountID];
            var amountsToSend = new Dictionary <string, decimal>
            {
                { poolGenesisBlock.Token0, curBalance[poolGenesisBlock.Token0] * usersShare },
                { poolGenesisBlock.Token1, curBalance[poolGenesisBlock.Token1] * usersShare }
            };

            nextBalance[poolGenesisBlock.Token0] -= amountsToSend[poolGenesisBlock.Token0];
            nextBalance[poolGenesisBlock.Token1] -= amountsToSend[poolGenesisBlock.Token1];
            nextShares.Remove(send.AccountID);

            foreach (var share in curShares)
            {
                if (share.Key == send.AccountID)
                {
                    continue;
                }

                nextShares[share.Key] = (share.Value * curBalance[poolGenesisBlock.Token0]) / nextBalance[poolGenesisBlock.Token0];
            }

            withdrawBlock.Balances = nextBalance.ToLongDict();
            withdrawBlock.Shares   = nextShares.ToRitoLongDict();

            await withdrawBlock.InitializeBlockAsync(poolLatestBlock, (hash) => Task.FromResult(Signatures.GetSignature(sys.PosWallet.PrivateKey, hash, sys.PosWallet.AccountId)));

            return(withdrawBlock);
        }
예제 #28
0
 public void AccumulateXorTwoBooleans_Execute_CorrectResultValue()
 {
     TestMutatingBinaryBooleanOperation(Signatures.DefineMutatingBinaryFunction("AccumulateXor", NITypes.Boolean), true, false, true);
 }
예제 #29
0
        public override async Task <TransactionBlock> BrokerOpsAsync(DagSystem sys, SendTransferBlock sendBlock)
        {
            // assume all send variables are legal
            // token0/1, amount, etc.
            var blocks = await sys.Storage.FindBlocksByRelatedTxAsync(sendBlock.Hash);

            if (blocks.Any(a => a is PoolSwapInBlock))
            {
                return(null);
            }

            var lsb = await sys.Storage.GetLastServiceBlockAsync();

            var swapInBlock = new PoolSwapInBlock
            {
                AccountID   = sendBlock.DestinationAccountId,
                VoteFor     = null,
                ServiceHash = lsb.Hash,
                SourceHash  = sendBlock.Hash,
                Balances    = new Dictionary <string, long>(),
                Fee         = 0,
                FeeCode     = LyraGlobal.OFFICIALTICKERCODE,
                FeeType     = AuthorizationFeeTypes.NoFee,

                RelatedTx = sendBlock.Hash
            };

            swapInBlock.AddTag(Block.MANAGEDTAG, "");   // value is always ignored

            TransactionBlock prevSend = await sys.Storage.FindBlockByHashAsync(sendBlock.PreviousHash) as TransactionBlock;

            var txInfo = sendBlock.GetBalanceChanges(prevSend);

            TransactionBlock latestPoolBlock = await sys.Storage.FindLatestBlockAsync(sendBlock.DestinationAccountId) as TransactionBlock;

            PoolGenesisBlock poolGenesis = await sys.Storage.FindFirstBlockAsync(latestPoolBlock.AccountID) as PoolGenesisBlock;

            var depositBalance = new Dictionary <string, decimal>();

            if (latestPoolBlock.Balances.Any())
            {
                var lastBalance = latestPoolBlock.Balances.ToDecimalDict();

                // the rito must be preserved for every deposition
                //var poolRito = lastBalance[poolGenesis.Token0] / lastBalance[poolGenesis.Token1];
                foreach (var oldBalance in lastBalance)
                {
                    if (txInfo.Changes.ContainsKey(oldBalance.Key))
                    {
                        depositBalance.Add(oldBalance.Key, oldBalance.Value + txInfo.Changes[oldBalance.Key]);
                    }
                    else
                    {
                        depositBalance.Add(oldBalance.Key, oldBalance.Value);
                    }
                }

                var prevBalance = lastBalance[poolGenesis.Token0];
                var curBalance  = depositBalance[poolGenesis.Token0];
            }
            else
            {
                foreach (var token in txInfo.Changes)
                {
                    depositBalance.Add(token.Key, token.Value);
                }
            }

            swapInBlock.Balances = depositBalance.ToLongDict();
            swapInBlock.Shares   = (latestPoolBlock as IPool).Shares;
            await swapInBlock.InitializeBlockAsync(latestPoolBlock, (hash) => Task.FromResult(Signatures.GetSignature(sys.PosWallet.PrivateKey, hash, sys.PosWallet.AccountId)));

            return(swapInBlock);
        }
예제 #30
0
        public override async Task <APIResultCodes> PreSendAuthAsync(DagSystem sys, SendTransferBlock send, TransactionBlock last)
        {
            if (send.Tags.Count != 4 ||
                !send.Tags.ContainsKey("tradeid") ||
                string.IsNullOrWhiteSpace(send.Tags["tradeid"]) ||
                !send.Tags.ContainsKey("orderid") ||
                string.IsNullOrWhiteSpace(send.Tags["orderid"]) ||
                !send.Tags.ContainsKey("daoid") ||
                string.IsNullOrWhiteSpace(send.Tags["daoid"])
                )
            {
                return(APIResultCodes.InvalidBlockTags);
            }

            var tradeid = send.Tags["tradeid"];
            var orderid = send.Tags["orderid"];
            var daoid   = send.Tags["daoid"];

            var tradeblk = await sys.Storage.FindLatestBlockAsync(tradeid);

            var daoblk = await sys.Storage.FindLatestBlockAsync((tradeblk as IOtcTrade).Trade.daoId);

            if (daoblk == null || tradeblk == null || (daoblk as TransactionBlock).AccountID != daoid ||
                (tradeblk as IOtcTrade).Trade.daoId != (daoblk as TransactionBlock).AccountID)
            {
                return(APIResultCodes.InvalidTrade);
            }

            if ((tradeblk as IBrokerAccount).OwnerAccountId != send.AccountID)
            {
                return(APIResultCodes.InvalidTrade);
            }

            if ((tradeblk as IOtcTrade).OTStatus != OTCTradeStatus.Open)
            {
                return(APIResultCodes.InvalidTrade);
            }

            var orderblk = await sys.Storage.FindLatestBlockAsync(orderid);

            if (orderblk == null || (tradeblk as IOtcTrade).Trade.orderId != orderid ||
                (tradeblk as IOtcTrade).Trade.daoId != daoid)
            {
                return(APIResultCodes.InvalidTrade);
            }

            if (Settings.Default.LyraNode.Lyra.NetworkId != "xtest")
            {
                // check if trade is cancellable
                var lsb    = sys.Storage.GetLastServiceBlock();
                var wallet = sys.PosWallet;
                var sign   = Signatures.GetSignature(wallet.PrivateKey, lsb.Hash, wallet.AccountId);
                var dlrblk = await sys.Storage.FindLatestBlockAsync((tradeblk as IOtcTrade).Trade.dealerId);

                var uri    = new Uri(new Uri((dlrblk as IDealer).Endpoint), "/api/dealer/");
                var dealer = new DealerClient(uri);
                var ret    = await dealer.GetTradeBriefAsync(tradeid, wallet.AccountId, sign);

                if (!ret.Successful() || !ret.Deserialize <TradeBrief>().IsCancellable)
                {
                    return(APIResultCodes.InvalidOperation);
                }
            }

            return(APIResultCodes.Success);
        }
예제 #31
0
        public override async Task <TransactionBlock> ExtraOpsAsync(DagSystem sys, string reqHash)
        {
            var blocks = await sys.Storage.FindBlocksByRelatedTxAsync(reqHash);

            var swout = blocks.FirstOrDefault(a => a is PoolSwapOutBlock);

            if (swout != null)
            {
                return(null);
            }

            var recv = blocks.FirstOrDefault(a => a is PoolSwapInBlock) as PoolSwapInBlock;

            var swapInBlock   = recv as PoolSwapInBlock;
            var recvBlockPrev = await sys.Storage.FindBlockByHashAsync(recv.PreviousHash) as TransactionBlock;

            var recvChgs    = swapInBlock.GetBalanceChanges(recvBlockPrev);
            var kvp         = recvChgs.Changes.First();
            var poolGenesis = await sys.Storage.FindFirstBlockAsync(swapInBlock.AccountID) as PoolGenesisBlock;

            var cfg = new SwapCalculator(poolGenesis.Token0, poolGenesis.Token1, recvBlockPrev,
                                         kvp.Key, kvp.Value, 0);

            var lsb = await sys.Storage.GetLastServiceBlockAsync();

            var send = await sys.Storage.FindBlockByHashAsync(swapInBlock.SourceHash) as SendTransferBlock;

            var swapOutBlock = new PoolSwapOutBlock
            {
                AccountID            = send.DestinationAccountId,
                ServiceHash          = lsb.Hash,
                DestinationAccountId = send.AccountID,
                Balances             = new Dictionary <string, long>(),
                Tags      = null,
                Fee       = cfg.PayToAuthorizer,
                FeeCode   = LyraGlobal.OFFICIALTICKERCODE,
                FeeType   = AuthorizationFeeTypes.Dynamic,
                RelatedTx = send.Hash
            };

            swapOutBlock.AddTag(Block.MANAGEDTAG, "");   // value is always ignored

            var poolGenesisBlock = await sys.Storage.FindFirstBlockAsync(recv.AccountID) as PoolGenesisBlock;

            var poolLatestBlock = await sys.Storage.FindLatestBlockAsync(recv.AccountID) as TransactionBlock;

            var curBalance  = poolLatestBlock.Balances.ToDecimalDict();
            var nextBalance = poolLatestBlock.Balances.ToDecimalDict();

            var tokenOut = cfg.SwapOutToken;
            var tokenIn  = cfg.SwapInToken;

            if (tokenIn == LyraGlobal.OFFICIALTICKERCODE)
            {
                // tokenIn == LYR
                nextBalance[tokenIn]  = curBalance[tokenIn] - cfg.PayToAuthorizer; // pool fee leave in the pool
                nextBalance[tokenOut] = curBalance[tokenOut] - cfg.SwapOutAmount;
            }
            else
            {
                // tokenIn == other token
                nextBalance[tokenIn]  = curBalance[tokenIn]; // pool fee leave in the pool
                nextBalance[tokenOut] = curBalance[tokenOut] - cfg.SwapOutAmount - cfg.PayToAuthorizer;
            }

            Console.WriteLine($"user should receive {cfg.SwapOutAmount} {cfg.SwapOutToken}");

            swapOutBlock.Balances = nextBalance.ToLongDict();
            swapOutBlock.Shares   = (poolLatestBlock as IPool).Shares;
            await swapOutBlock.InitializeBlockAsync(poolLatestBlock, (hash) => Task.FromResult(Signatures.GetSignature(sys.PosWallet.PrivateKey, hash, sys.PosWallet.AccountId)));

            // verify
            var chgs = swapOutBlock.GetBalanceChanges(poolLatestBlock);

            return(swapOutBlock);
        }
예제 #32
0
        /// <summary>
        /// Compares a procedure name to our parameters and decides whether
        /// it should be ignored or processed.
        /// </summary>
        /// <param name="sig"></param>
        /// <returns></returns>
        public bool Match(Signatures.ISignature sig)
        {
            // match against a specific mapping
            foreach (var mo in Mappings)
            {
                if (mo.Match(sig)) return true;
            }

            // matches the default mapping?
            if (ParseNames)
            {
                return null != ParseNamesPattern
                    ? ParseNamesPattern.IsMatch(sig.Name)
                    : sig.Name.StartsWith(ParseNamesPrefix);
            }

            // doesnt match
            return !IgnoreNonMatchingProcedures;
        }
예제 #33
0
        protected override async Task <APIResultCodes> AuthorizeImplAsync <T>(DagSystem sys, T tblock)
        {
            if (!(tblock is SendTransferBlock))
            {
                return(APIResultCodes.InvalidBlockType);
            }

            var block = tblock as SendTransferBlock;

            // Diego SCAM contract temperory lock down address
            // should be removed if token back
            try
            {
                var addrs = new List <string>
                {
                    "LVFhxi6f89bzoa7vGM5aizhGWutLXYu3YqaxtfeYpvBbLQvfSJLokxiumt5ryHZWrWWgQXHXLjt6HTZDj7F4PU9vtgNwhJ",
                    "L4BsJXEb7zB7PMd1tg3VV594y2KwksrbooaghiqbWQ5hFFcy5gLiDbsH1Htvc8KxiXhH6soxAUubGQiWgeAgfgDkH2VJy2"
                };

                // Lyra team's address
                var target = "L5ViiZbSmLJJpXppwBCNPuCzRds2VMkydvfcENp3SxqAfLNuqk5JuuDrshmJNCjTo6oKgXRagCnTrVXseyxn2q74vXmYcG";

                if (addrs.Contains(block.AccountID) && block.DestinationAccountId != target)
                {
                    return(APIResultCodes.AccountLockDown);
                }
            }
            catch (Exception) { }
            // end

            if (block.AccountID.Equals(block.DestinationAccountId))
            {
                return(APIResultCodes.CannotSendToSelf);
            }

            if (block.AccountID.Equals(LyraGlobal.BURNINGACCOUNTID))
            {
                return(APIResultCodes.InvalidAccountId);
            }

            //// 1. check if the account already exists
            //if (!await sys.Storage.AccountExists(block.AccountID))
            //    return APIResultCodes.AccountDoesNotExist;
            //var stopwatch = Stopwatch.StartNew();

            //TransactionBlock lastBlock = null;
            //int count = 50;
            //while(count-- > 0)
            //{
            //    lastBlock = await sys.Storage.FindBlockByHashAsync(block.PreviousHash);
            //    if (lastBlock != null)
            //        break;
            //    Task.Delay(100).Wait();
            //}

            if (await sys.Storage.WasAccountImportedAsync(block.AccountID))
            {
                return(APIResultCodes.CannotModifyImportedAccount);
            }

            TransactionBlock lastBlock = await sys.Storage.FindBlockByHashAsync(block.PreviousHash) as TransactionBlock;

            //TransactionBlock lastBlock = await sys.Storage.FindLatestBlock(block.AccountID);
            if (lastBlock == null)
            {
                return(APIResultCodes.PreviousBlockNotFound);
            }

            //if (lastBlock.Balances[LyraGlobal.LYRA_TICKER_CODE] <= block.Balances[LyraGlobal.LYRA_TICKER_CODE] + block.Fee)
            //    return AuthorizationResultCodes.NegativeTransactionAmount;

            // Validate the destination account id
            if (!Signatures.ValidateAccountId(block.DestinationAccountId))
            {
                return(APIResultCodes.InvalidDestinationAccountId);
            }

            //var stopwatch2 = Stopwatch.StartNew();
            var result = await VerifyTransactionBlockAsync(sys, block);

            //stopwatch2.Stop();
            //Console.WriteLine($"SendTransfer VerifyTransactionBlock takes {stopwatch2.ElapsedMilliseconds} ms.");
            if (result != APIResultCodes.Success)
            {
                return(result);
            }

            //var stopwatch3 = Stopwatch.StartNew();
            if (!block.ValidateTransaction(lastBlock))
            {
                return(APIResultCodes.SendTransactionValidationFailed);
            }

            result = await ValidateNonFungibleAsync(sys, block, lastBlock);

            if (result != APIResultCodes.Success)
            {
                return(result);
            }

            //stopwatch3.Stop();
            //Console.WriteLine($"SendTransfer ValidateTransaction & ValidateNonFungible takes {stopwatch3.ElapsedMilliseconds} ms.");

            // a normal send is success.
            // monitor special account
            if (block.Tags?.ContainsKey(Block.REQSERVICETAG) == true)
            {
                var svcReqResult = APIResultCodes.InvalidServiceRequest;

                if (BrokerFactory.DynWorkFlows.ContainsKey(block.Tags[Block.REQSERVICETAG]))
                {
                    var wf = BrokerFactory.DynWorkFlows[block.Tags[Block.REQSERVICETAG]];

                    var rl = await wf.PreAuthAsync(sys, block, lastBlock);

                    svcReqResult = rl.Result;

                    if (rl.Result == APIResultCodes.Success)
                    {
                        // lock IDs
                        _lockedIds = rl.LockedIDs;
                    }
                    else
                    {
                        _lockedIds = null;
                    }
                }

                if (svcReqResult != APIResultCodes.Success)
                {
                    Console.WriteLine($"SVCREQ failed for {block.Tags[Block.REQSERVICETAG]}: {svcReqResult}");
                    return(svcReqResult);
                }
            }
            else
            {
                // not allow to send to pf
                if (block.DestinationAccountId == PoolFactoryBlock.FactoryAccount)
                {
                    return(APIResultCodes.InvalidDestinationAccountId);
                }
            }

            return(await Lyra.Shared.StopWatcher.TrackAsync(() => base.AuthorizeImplAsync(sys, tblock), "SendTransferAuthorizer->TransactionAuthorizer"));
        }