public async Task <ActionResult <FullUser> > CreateCornaddy([FromBody] CreateCornaddyRequest request) { try { if (string.IsNullOrWhiteSpace(request.Id)) { throw new ArgumentNullException("id"); } var platformId = BitcornUtils.GetPlatformId(request.Id); var user = await BitcornUtils.GetUserForPlatform(platformId, _dbContext).FirstOrDefaultAsync(); if (user != null) { var walletResponse = await WalletUtils.CreateCornaddy(_dbContext, user.UserWallet, _configuration); if (!walletResponse.WalletAvailable) { return(StatusCode((int)HttpStatusCode.ServiceUnavailable)); } return(BitcornUtils.GetFullUser(user, user.UserIdentity, user.UserWallet, user.UserStat)); } else { return(StatusCode(500)); } } catch (Exception e) { await BITCORNLogger.LogError(_dbContext, e); throw e; } }
public static async Task Execute() { Console.WriteLine("Wallet sample -> started"); var firstWalletConfig = "{\"id\":\"my_wallet\"}"; var secondWalletConfig = "{\"id\":\"their_wallet\"}"; var firstWalletCredentials = "{\"key\":\"my_wallet_key\"}"; var secondWalletCredentials = "{\"key\":\"their_wallet_key\"}"; try { // Create and Open First Wallet await WalletUtils.CreateWalletAsync(firstWalletConfig, firstWalletCredentials); using (var firstWallet = await Wallet.OpenWalletAsync(firstWalletConfig, firstWalletCredentials)) { // Create a DID that we will retrieve and compare from imported wallet var myDid = await Did.CreateAndStoreMyDidAsync(firstWallet, "{}"); var path = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var exportConfig = JsonConvert.SerializeObject(new { path = path, key = Guid.NewGuid().ToString() }); await firstWallet.ExportAsync(exportConfig); // Import the exported wallet into a new wallet await Wallet.ImportAsync(secondWalletConfig, secondWalletCredentials, exportConfig); // Open the second wallet using (var secondWallet = await Wallet.OpenWalletAsync(secondWalletConfig, secondWalletCredentials)) { // Retrieve stored key var myKey = await Did.KeyForLocalDidAsync(secondWallet, myDid.Did); // Compare the two keys Debug.Assert(myKey == myDid.VerKey); await secondWallet.CloseAsync(); } // Close wallets await firstWallet.CloseAsync(); File.Delete(path); } } finally { // 11. Delete wallets and Pool ledger config await WalletUtils.DeleteWalletAsync(firstWalletConfig, firstWalletCredentials); await WalletUtils.DeleteWalletAsync(secondWalletConfig, secondWalletCredentials); } Console.WriteLine("Wallet sample -> completed"); }
public async Task TestProverStoreClaimWorks() { await InitCommonWallet(); await WalletUtils.CreateWallet(WALLET_NAME, WALLET_KEY); var proverWallet = await WalletUtils.OpenWallet(WALLET_NAME, WALLET_KEY); await AnonCreds.ProverCreateMasterSecretAsync(proverWallet, masterSecretName); var claimOffer = string.Format(claimOfferTemplate, issuerDid, 1); var claimRequest = await AnonCreds.ProverCreateCredentialReqAsync(proverWallet, proverDid, claimOffer, claimDef, masterSecretName); var claim = "{\"sex\":[\"male\",\"5944657099558967239210949258394887428692050081607692519917050011144233115103\"],\n" + " \"name\":[\"Alex\",\"1139481716457488690172217916278103335\"],\n" + " \"height\":[\"175\",\"175\"],\n" + " \"age\":[\"28\",\"28\"]\n" + " }"; // TODO var createClaimResult = await AnonCreds.IssuerCreateCredentialAsync(commonWallet, claimRequest, claim, -1); // var claimJson = createClaimResult.ClaimJson; // TODO await AnonCreds.ProverStoreClaimAsync(proverWallet, claimJson, createClaimResult.RevocRegUpdateJson); await proverWallet.CloseAsync(); await WalletUtils.DeleteWallet(WALLET_NAME, WALLET_KEY); }
/// <summary> /// Checks if data already exists in the DynamicDataCache. /// If the data is equal to the mnemonic entered in the input fields, display the ConfirmMnemonicMenu. /// </summary> /// <returns> True if the mnemonic was unique and the wallet can be directly imported. </returns> private bool CheckCreatedMnemonic() { Wallet wallet = null; string newMnemonic = string.Join(" ", wordFields.Select(field => field.Text)).Trim(); byte[] seed = (byte[])dynamicDataCache.GetData("seed"); try { wallet = new Wallet(newMnemonic, null, WalletUtils.DetermineCorrectPath(newMnemonic)); nextButton.GetComponent <InteractableButton>().OnCustomPointerExit(); } catch { nextButton.interactable = false; importMneomonicMenuAnimator.AnimateIcon(importMneomonicMenuAnimator.nextButtonErrorIcon); importMneomonicMenuAnimator.AnimateIcon(importMneomonicMenuAnimator.nextButtonErrorMessage); importMneomonicMenuAnimator.OpeningWallet = false; return(false); } if (seed?.SequenceEqual(wallet.Seed) == true) { uiManager.OpenMenu <ConfirmMnemonicMenu>(); return(false); } else { SetWalletInfo(wallet); return(true); } }
public async Task TestWithdrawInsufficientFunds() { var dbContext = TestUtils.CreateDatabase(); try { var user = dbContext.TwitchQuery(_configuration["Config:TestFromUserId"]).FirstOrDefault(); var amount = user.UserWallet.Balance.Value + 10; var server = dbContext.WalletServer.FirstOrDefault(u => u.Index == user.UserWallet.WalletServer); await WalletUtils.DebitWithdrawTx("test", user, server, amount, dbContext, "test"); using (var dbContext2 = TestUtils.CreateDatabase()) { var user2 = dbContext2.TwitchQuery(_configuration["Config:TestFromUserId"]).FirstOrDefault(); var server2 = dbContext2.WalletServer.FirstOrDefault(u => u.Index == user.UserWallet.WalletServer); Assert.Equal(user.UserWallet.Balance, user2.UserWallet.Balance); Assert.Equal(server.ServerBalance, server2.ServerBalance); } } finally { dbContext.Dispose(); } }
public static void CreateWalletToKeystoreFile(string[] args) { if (args.Length < 2) { WriteLine("You have input invalid parameters."); Environment.Exit(0); } WalletInfo walletInfo = WalletUtils.CreateWallet(args[1]); byte[] rawPrivateKey = walletInfo.KeyPair.GetRawPrivateKey(); string newPrivateKey = ByteUtils.ToHexString(rawPrivateKey, Prefix.ZeroLowerX); string keyStoreStr = walletInfo.ToKeystoreString(); string path = "./keystore.json"; if (args.Length > 2) { path = args[2]; } var parent = Directory.GetDirectoryRoot(path); if (!string.IsNullOrEmpty(parent)) { Directory.CreateDirectory(parent); } File.WriteAllText(path, keyStoreStr); WriteLine("The wallet created successfully and the key store is:"); WriteLine(keyStoreStr); WriteLine("The wallet created successfully and the privateKey is:"); WriteLine(newPrivateKey); }
public async Task <ActionResult> Deposit([FromBody] WalletDepositRequest request) { try { var receipts = await WalletUtils.Deposit(_dbContext, request); foreach (var receipt in receipts) { var identity = await _dbContext.UserIdentity.FirstOrDefaultAsync(u => u.UserId == receipt.ReceiverId); await BitcornUtils.TxTracking(_configuration, new { txid = receipt.BlockchainTxId, time = DateTime.Now, method = "deposit", platform = "wallet-server", amount = receipt.Amount, userid = receipt.ReceiverId, twitchUsername = identity.TwitchUsername, discordUsername = identity.DiscordUsername }); } return(Ok()); } catch (Exception e) { await BITCORNLogger.LogError(_dbContext, e); throw e; } }
public static async Task Execute() { Console.Write("Executing non-secrets sample... "); var myWalletConfig = "{\"id\":\"my_wallet\"}"; var myWalletCredentials = "{\"key\":\"my_wallet_key\"}"; try { // Create and Open First Wallet await WalletUtils.CreateWalletAsync(myWalletConfig, myWalletCredentials); using (var myWallet = await Wallet.OpenWalletAsync(myWalletConfig, myWalletCredentials)) { var id = "myRecordId"; var value = "myRecordValue"; var type = "record_type"; var tagsJson = JsonConvert.SerializeObject(new { tagName = "tagValue", tagName2 = "tagValue2" }); var queryJson = JsonConvert.SerializeObject(new { tagName = "tagValue" }); // Add a new record to the wallet await NonSecrets.AddRecordAsync(myWallet, type, id, value, tagsJson); // Retrieve the record by type and id var recordJson = await NonSecrets.GetRecordAsync(myWallet, type, id, "{}"); var record = JObject.Parse(recordJson); Debug.Assert(record["id"].ToObject <string>() == id); Debug.Assert(record["value"].ToObject <string>() == value); // Open wallet search inside using statement to properly dispose and close the search handle using (var walletSearch = await NonSecrets.OpenSearchAsync(myWallet, type, queryJson, "{}")) { // Invoke fetch next records var searchJson = await walletSearch.NextAsync(myWallet, 5); var search = JObject.Parse(searchJson); // There should be one record returned Debug.Assert(search["records"].ToObject <JObject[]>().Length == 1); } // Close wallets await myWallet.CloseAsync(); } Console.WriteLine("OK", Color.Green); } catch (Exception e) { Console.WriteLine($"Error: {e.Message}", Color.Red); } finally { // Delete wallets await WalletUtils.DeleteWalletAsync(myWalletConfig, myWalletCredentials); } }
public async Task DeleteWallet() { if (_wallet != null) { await _wallet.CloseAsync(); } await WalletUtils.DeleteWallet(WALLET_NAME, WALLET_KEY); }
public async Task Cleanup() { await wallet.CloseAsync(); await pool.CloseAsync(); await WalletUtils.DeleteWalletAsync(myWalletName, null); await PoolUtils.DeletePoolLedgerConfigAsync(PoolUtils.DEFAULT_POOL_NAME); }
public async Task TestCreateWalletWorksForUnknownType() { var config = JsonConvert.SerializeObject(new { id = WalletUtils.GetWalletId(), storage_type = "unknown_type" }); var ex = await Assert.ThrowsExceptionAsync <UnknownWalletTypeException>(() => Wallet.CreateWalletAsync(config, WALLET_CREDENTIALS) ); }
public async Task <object> Withdraw([FromBody] WithdrawRequest request) { try { var platformId = BitcornUtils.GetPlatformId(request.Id); var user = await BitcornUtils.GetUserForPlatform(platformId, _dbContext).FirstOrDefaultAsync(); var response = new Dictionary <string, object>(); if (user != null) { var withdrawResult = await WalletUtils.Withdraw(_dbContext, _configuration, user, request.CornAddy, request.Amount, platformId.Platform); response.Add("usererror", withdrawResult.UserError); response.Add("walletavailable", withdrawResult.WalletAvailable); response.Add("txid", withdrawResult.WalletObject); if (request.Columns.Length > 0) { var columns = await UserReflection.GetColumns(_dbContext, request.Columns, new int[] { user.UserId }); if (columns.Count > 0) { foreach (var item in columns.First().Value) { response.Add(item.Key, item.Value); } } } if (withdrawResult.WalletObject != null && request.Amount > 100000) { await BitcornUtils.TxTracking(_configuration, new { txid = withdrawResult.WalletObject, time = DateTime.Now, method = "withdraw", platform = platformId.Platform, amount = request.Amount, userid = user.UserId, twitchUsername = user.UserIdentity.TwitchUsername, discordUsername = user.UserIdentity.DiscordUsername, cornaddy = request.CornAddy, }); } } return(response); } catch (Exception e) { await BITCORNLogger.LogError(_dbContext, e); throw e; } }
//[ReflectionProtect] private void GetConfirmationWords() { string[] correctWords; int[] numbers = dynamicDataCache.GetData("confirmation numbers"); List <int> randomIntList = numbers.ToList(); List <string> words = WalletUtils.GetMnemonicWords((string)dynamicDataCache.GetData("mnemonic")).ToList(); correctWords = words.Where(word => numbers.Contains(words.IndexOf(word) + 1)) .OrderBy(word => randomIntList.IndexOf(words.IndexOf(word) + 1)) .ToArray(); dynamicDataCache.SetData("confirmation words", correctWords); }
public async Task Before() { StorageUtils.CleanupStorage(); //1. Create Issuer wallet, get wallet handle await WalletUtils.CreateWallet(WALLET_NAME, WALLET_KEY); _issuerWallet = await WalletUtils.OpenWallet(WALLET_NAME, WALLET_KEY); //2. Issuer create claim definition IssuerCreateAndStoreCredentialDefResult result = await AnonCreds.IssuerCreateAndStoreCredentialDefAsync(_issuerWallet, issuerDid, schema, null, null, null); _claimDefJson = result.CredDefJson; //3. Issuer create revocation registry BlobStorageWriter tailsWriter = await BlobStorage.OpenWriterAsync("default", _tailsWriterConfig); await AnonCreds.IssuerCreateAndStoreRevocRegAsync(_issuerWallet, issuerDid, null, null, null, null, tailsWriter); //4. Prover create Master Secret await AnonCreds.ProverCreateMasterSecretAsync(_issuerWallet, masterSecretName); //5. Prover store Claim Offer received from Issuer var claimOfferJson = string.Format(claimOfferTemplate, issuerDid, 1); // TODO await AnonCreds.ProverStoreCredentialOfferAsync(_issuerWallet, claimOfferJson); //6. Prover create Claim Request var proverDid = "BzfFCYk"; var claimReq = await AnonCreds.ProverCreateCredentialReqAsync( _issuerWallet, proverDid, claimOfferJson, _claimDefJson, masterSecretName); //7. Issuer create Claim var claimJson = "{" + "\"sex\":[\"male\",\"5944657099558967239210949258394887428692050081607692519917050011144233115103\"]," + "\"name\":[\"Alex\",\"1139481716457488690172217916278103335\"]," + "\"height\":[\"175\",\"175\"]," + "\"age\":[\"28\",\"28\"]" + "}"; _claimResult = null; // TODO await AnonCreds.IssuerCreateCredentialAsync(_issuerWallet, claimReq, claimJson, _userRevocIndex); //8. Prover store received Claim // TODO await AnonCreds.ProverStoreClaimAsync(_issuerWallet, _claimResult.CredentialJson, _claimResult.RevocRegDeltaJson); }
//[ReflectionProtect] private void StartWordAnimation() { mnemonicWords = WalletUtils.GetMnemonicWords(dynamicDataCache.GetData("mnemonic")); wordFields.ForEach(f => f.AnimateColor(UIColors.White, 0.1f)); Animating = true; Random rand = new Random(); List <GameObject> randomizedWordList = new List <GameObject>(words); randomizedWordList.Sort((_, __) => rand.Next(-1, 1)); ProcessWordAnimation(randomizedWordList, 0); }
public async Task Initialize() { // 1. Create ledger config from genesis txn file await PoolUtils.CreatePoolLedgerConfig(); // 2. Create and Open My Wallet await WalletUtils.CreateWalletAsync(PoolUtils.DEFAULT_POOL_NAME, myWalletName, "default", null, null); //3. Open pool and wallets in using statements to ensure they are closed when finished. pool = await Pool.OpenPoolLedgerAsync(PoolUtils.DEFAULT_POOL_NAME, "{}"); wallet = await Wallet.OpenWalletAsync(myWalletName, null, null); Console.WriteLine($"Wallet and pool opened: {pool} {wallet}"); }
public async Task CreateWallet() { //1. Create and Open Pool _poolName = PoolUtils.CreatePoolLedgerConfig(); _pool = await Pool.OpenPoolLedgerAsync(_poolName, "{}"); //2. Issuer Create and Open Wallet await WalletUtils.CreateWallet(ISSUER_WALLET, ISSUER_WALLET_KEY); _issuerWallet = await WalletUtils.OpenWallet(ISSUER_WALLET, ISSUER_WALLET_KEY); //3. Prover Create and Open Wallet await WalletUtils.CreateWallet(PROVER_WALLET, PROVER_WALLET_KEY); _proverWallet = await WalletUtils.OpenWallet(PROVER_WALLET, PROVER_WALLET_KEY); }
public async Task TestGetClaimOffersForPlugged() { var type = "proverInmem"; var poolName = "default"; var walletName = "proverCustomWallet"; await WalletUtils.CreateWallet(WALLET_NAME, WALLET_KEY); string claimOffers = string.Empty; Wallet wallet = null; var claimOffer = string.Format(claimOfferTemplate, issuerDid, 1); var claimOffer2 = string.Format(claimOfferTemplate, issuerDid, 2); var claimOffer3 = string.Format(claimOfferTemplate, issuerDid2, 2); try { wallet = await WalletUtils.OpenWallet(WALLET_NAME, WALLET_KEY); // TODO await AnonCreds.ProverStoreCredentialOfferAsync(wallet, claimOffer); // TODO await AnonCreds.ProverStoreCredentialOfferAsync(wallet, claimOffer2); // TODO await AnonCreds.ProverStoreCredentialOfferAsync(wallet, claimOffer3); var filter = string.Format("{{\"issuer_did\":\"{0}\"}}", issuerDid); // TODO claimOffers = await AnonCreds.ProverGetClaimOffersAsync(wallet, filter); } finally { if (wallet != null) { await wallet.CloseAsync(); } await WalletUtils.DeleteWallet(WALLET_NAME, WALLET_KEY); } var claimOffersArray = JArray.Parse(claimOffers); Assert.AreEqual(2, claimOffersArray.Count); Assert.IsTrue(claimOffers.Contains(claimOffer)); Assert.IsTrue(claimOffers.Contains(claimOffer2)); }
public async Task <ActionResult <FullUser> > CreateCornaddy([FromBody] CreateCornaddyRequest request) { try { if (this.GetCachedUser() != null) { throw new InvalidOperationException(); } if (string.IsNullOrWhiteSpace(request.Id)) { throw new ArgumentNullException("id"); } var platformId = BitcornUtils.GetPlatformId(request.Id); var user = await BitcornUtils.GetUserForPlatform(platformId, _dbContext).FirstOrDefaultAsync(); if (user != null) { var walletResponse = await WalletUtils.CreateCornaddy(_dbContext, user.UserWallet, _configuration); if (!walletResponse.WalletAvailable) { user.UserWallet.CornAddy = "<no enabled wallets found>"; await _dbContext.SaveAsync(); return(StatusCode(200)); //return StatusCode((int)HttpStatusCode.ServiceUnavailable); } return(BitcornUtils.GetFullUser(user, user.UserIdentity, user.UserWallet, user.UserStat)); } else { return(StatusCode(500)); } } catch (Exception e) { await BITCORNLogger.LogError(_dbContext, e, JsonConvert.SerializeObject(request)); throw e; } }
private void UpdateWordFields() { for (int i = 0; i < objects.Length; i++) { wordFields.Add(objects[i].GetComponent <TMP_InputField>()); } string[] splitWords = WalletUtils.GetMnemonicWords(dynamicDataCache.GetData("mnemonic")); for (int i = 0; i < objects.Length; i++) { wordFields[i].text = splitWords[i]; } for (int i = 0; i < 12; i++) { wordFieldSelectables.Add(wordFields[i]); } }
protected async Task InitCommonWallet() { if (_walletOpened) { return; } StorageUtils.CleanupStorage(); await WalletUtils.CreateWallet(WALLET_NAME, WALLET_KEY); commonWallet = await WalletUtils.OpenWallet(WALLET_NAME, WALLET_KEY); IssuerCreateAndStoreCredentialDefResult claimDefType = await AnonCreds.IssuerCreateAndStoreCredentialDefAsync(commonWallet, issuerDid, schema, null, null, null); claimDef = claimDefType.CredDefJson; await AnonCreds.ProverStoreCredentialAsync(commonWallet, string.Format(claimOfferTemplate, issuerDid, 1), null, null, null, null); // TODO await AnonCreds.ProverStoreCredentialOfferAsync(commonWallet, string.Format(claimOfferTemplate, issuerDid, 2), null, null, null, null); // TODO await AnonCreds.ProverStoreCredentialOfferAsync(commonWallet, string.Format(claimOfferTemplate, issuerDid2, 2), null, null, null, null); await AnonCreds.ProverCreateMasterSecretAsync(commonWallet, masterSecretName); var claimOffer = string.Format("{{\"issuer_did\":\"{0}\",\"schema_seq_no\":{1}}}", issuerDid, 1); var claimRequest = await AnonCreds.ProverCreateCredentialReqAsync(commonWallet, "CnEDk9HrMnmiHXEV1WFgbVCRteYnPqsJwrTdcZaNhFVW", claimOffer, claimDef, masterSecretName); var claim = "{\"sex\":[\"male\",\"5944657099558967239210949258394887428692050081607692519917050011144233115103\"],\n" + " \"name\":[\"Alex\",\"1139481716457488690172217916278103335\"],\n" + " \"height\":[\"175\",\"175\"],\n" + " \"age\":[\"28\",\"28\"]\n" + " }"; //TODO var createClaimResult = await AnonCreds.IssuerCreateCredentialAsync(commonWallet, claimRequest, claim, -1); //TODO var claimJson = createClaimResult.ClaimJson; //TODO await AnonCreds.ProverStoreClaimAsync(commonWallet, claimJson, createClaimResult.RevocRegUpdateJson); _walletOpened = true; }
public async static void Execute(WalletUtils walletUtils) { // Console.WriteLine("SendCoinJob.Execute"); foreach (Recipient recp in Throttling.Transactions.Values) { // Console.WriteLine("Sending Transaction {0} ", recp.address); if (!recp.is_sent && !recp.is_error) { try { await walletUtils.SendCoin(recp); } catch (FaucetException e) { Console.WriteLine(e.Message); } } } Throttling.Manage(); }
public async Task DeleteWallet() { if (_issuerWallet != null) { await _issuerWallet.CloseAsync(); } await WalletUtils.DeleteWallet(ISSUER_WALLET, ISSUER_WALLET_KEY); if (_proverWallet != null) { await _proverWallet.CloseAsync(); } await WalletUtils.DeleteWallet(PROVER_WALLET, PROVER_WALLET_KEY); if (_pool != null) { await _pool.CloseAsync(); } }
public async Task TestSignAndSubmitRequestWorksForIncompatibleWalletAndPool() { var walletName = "incompatibleWallet"; await WalletUtils.CreateWallet(walletName, "walletKey1"); var wallet = await WalletUtils.OpenWallet(walletName, "walletKey1"); var trusteeDidResult = await Did.CreateAndStoreMyDidAsync(wallet, TRUSTEE_IDENTITY_JSON); var trusteeDid = trusteeDidResult.Did; var myDidResult = await Did.CreateAndStoreMyDidAsync(wallet, "{}"); var myDid = myDidResult.Did; var nymRequest = await Ledger.BuildNymRequestAsync(trusteeDid, myDid, null, null, null); var ex = await Assert.ThrowsExceptionAsync <WrongWalletForPoolException>(() => Ledger.SignAndSubmitRequestAsync(pool, wallet, trusteeDid, nymRequest) ); }
/// <summary> /// Splits the copied string on the clipboard into an array and sets them individually during the animations /// </summary> private void PastePhraseClicked() { string clipboard = ClipboardUtils.GetClipboardString(); wordStrings = WalletUtils.GetMnemonicWords(clipboard); if (!string.IsNullOrEmpty(clipboard.Trim())) { int numOfWords = wordStrings.Length; wordCountSection.GetComponent <SingleChoiceButtonsBase>().ButtonClicked(numOfWords <= 12 ? 0 : numOfWords <= 15 ? 1 : numOfWords <= 18 ? 2 : numOfWords <= 21 ? 3 : 4); AnimateIcon(pasteButtonCheckMarkIcon); StartWordAnimation(); } else { if (!animatingIcon) { AnimateIcon(pasteButtonErrorIcon); } } }
protected override InteropTransaction PullPlatformTransaction(string platformName, Hash hash) { foreach (var swap in _swaps) { if (swap.platformName == platformName && swap.hash == hash) { var info = Nexus.GetPlatformInfo(platformName); var platformAddress = info.Address; string destAddress; string temp; WalletUtils.DecodePlatformAndAddress(info.Address, out temp, out destAddress); var token = Nexus.GetTokenInfo(swap.symbol); var amount = UnitConversion.ToBigInteger(swap.amount, token.Decimals); return(new InteropTransaction() { Platform = platformName, Hash = hash, Events = new Event[] { new Event(EventKind.TokenSend, WalletUtils.EncodeAddress(swap.sourceAddress, platformName), "swap", Serialization.Serialize(new TokenEventData() { chainAddress = platformAddress, symbol = swap.symbol, value = amount })), new Event(EventKind.TokenReceive, WalletUtils.EncodeAddress(destAddress, platformName), "swap", Serialization.Serialize(new TokenEventData() { chainAddress = platformAddress, symbol = swap.symbol, value = amount })) } }); } } throw new OracleException($"unknown transaction for {platformName} : {hash}"); }
public static async Task Execute() { Console.WriteLine("Ledger sample -> started"); var myWalletName = "myWallet"; var theirWalletName = "theirWallet"; try { //1. Create and Open Pool await PoolUtils.CreatePoolLedgerConfig(); //2. Create and Open My Wallet await WalletUtils.CreateWalleatAsync(PoolUtils.DEFAULT_POOL_NAME, myWalletName, "default", null, null); // 3. Create and Open Trustee Wallet await WalletUtils.CreateWalleatAsync(PoolUtils.DEFAULT_POOL_NAME, theirWalletName, "default", null, null); //4. Open pool and wallets in using statements to ensure they are closed when finished. using (var pool = await Pool.OpenPoolLedgerAsync(PoolUtils.DEFAULT_POOL_NAME, "{}")) using (var myWallet = await Wallet.OpenWalletAsync(myWalletName, null, null)) using (var theirWallet = await Wallet.OpenWalletAsync(theirWalletName, null, null)) { //5. Create My Did var createMyDidResult = await Signus.CreateAndStoreMyDidAsync(myWallet, "{}"); //6. Create Their Did var createTheirDidResult = await Signus.CreateAndStoreMyDidAsync(theirWallet, "{}"); var theirDid = createTheirDidResult.Did; var theirVerkey = createTheirDidResult.VerKey; //7. Store Their DID var identityJson = string.Format("{{\"did\":\"{0}\", \"verkey\":\"{1}\"}}", theirDid, theirVerkey); await Signus.StoreTheirDidAsync(myWallet, identityJson); //8. Their sign message var msgBytes = Encoding.UTF8.GetBytes("{\n" + " \"reqId\":1495034346617224651,\n" + " \"identifier\":\"GJ1SzoWzavQYfNL9XkaJdrQejfztN4XqdsiV4ct3LXKL\",\n" + " \"operation\":{\n" + " \"type\":\"1\",\n" + " \"dest\":\"4efZu2SXufS556yss7W5k6Po37jt4371RM4whbPKBKdB\"\n" + " }\n" + "}"); var signatureBytes = await Signus.SignAsync(theirWallet, theirDid, msgBytes); //9. Verify message var valid = await Signus.VerifySignatureAsync(myWallet, pool, theirDid, msgBytes, signatureBytes); Debug.Assert(valid == true); //10. Close wallets and pool await myWallet.CloseAsync(); await theirWallet.CloseAsync(); await pool.CloseAsync(); } } finally { // 12. Delete wallets and Pool ledger config await WalletUtils.DeleteWalletAsync(myWalletName, null); await WalletUtils.DeleteWalletAsync(theirWalletName, null); await PoolUtils.DeletePoolLedgerConfigAsync(PoolUtils.DEFAULT_POOL_NAME); } Console.WriteLine("Ledger sample -> completed"); }
public static async Task Execute() { Console.WriteLine("Anoncreds Revocation sample -> started"); var issuerWalletName = "issuerWallet"; var proverWalletName = "proverWallet"; var issuerWalletCredentials = "{\"key\":\"issuer_wallet_key\"}"; var proverWalletCredentials = "{\"key\":\"prover_wallet_key\"}"; var issuerDid = "NcYxiDXkpYi6ov5FcYDi1e"; var proverDid = "VsKV7grR1BUE29mG2Fm2kX"; try { //1. Create and Open Pool await PoolUtils.CreatePoolLedgerConfig(); //2. Issuer Create and Open Wallet await WalletUtils.CreateWalletAsync(PoolUtils.DEFAULT_POOL_NAME, issuerWalletName, "default", null, issuerWalletCredentials); //3. Prover Create and Open Wallet await WalletUtils.CreateWalletAsync(PoolUtils.DEFAULT_POOL_NAME, proverWalletName, "default", null, proverWalletCredentials); // Open pool and wallets in using statements to ensure they are closed when finished. using (var pool = await Pool.OpenPoolLedgerAsync(PoolUtils.DEFAULT_POOL_NAME, "{}")) using (var issuerWallet = await Wallet.OpenWalletAsync(issuerWalletName, null, issuerWalletCredentials)) using (var proverWallet = await Wallet.OpenWalletAsync(proverWalletName, null, proverWalletCredentials)) { //4. Issuer Creates Credential Schema var schemaName = "gvt"; var schemaVersion = "1.0"; var schemaAttributes = "[\"name\", \"age\", \"sex\", \"height\"]"; var createSchemaResult = await AnonCreds.IssuerCreateSchemaAsync(issuerDid, schemaName, schemaVersion, schemaAttributes); var schemaId = createSchemaResult.SchemaId; var schemaJson = createSchemaResult.SchemaJson; //5. Issuer create Credential Definition var credDefTag = "Tag1"; var credDefConfigJson = "{\"support_revocation\":true}"; var createCredDefResult = await AnonCreds.IssuerCreateAndStoreCredentialDefAsync(issuerWallet, issuerDid, schemaJson, credDefTag, null, credDefConfigJson); var credDefId = createCredDefResult.CredDefId; var credDefJson = createCredDefResult.CredDefJson; //6. Issuer create Revocation Registry var revRegDefConfig = "{\"issuance_type\":\"ISSUANCE_ON_DEMAND\",\"max_cred_num\":5}"; var tailsWriterConfig = string.Format("{{\"base_dir\":\"{0}\", \"uri_pattern\":\"\"}}", EnvironmentUtils.GetIndyHomePath("tails")).Replace('\\', '/'); var tailsWriter = await BlobStorage.OpenWriterAsync("default", tailsWriterConfig); var revRegDefTag = "Tag2"; var createRevRegResult = await AnonCreds.IssuerCreateAndStoreRevocRegAsync(issuerWallet, issuerDid, null, revRegDefTag, credDefId, revRegDefConfig, tailsWriter); var revRegId = createRevRegResult.RevRegId; var revRegDefJson = createRevRegResult.RevRegDefJson; //7. Prover create Master Secret var masterSecretId = await AnonCreds.ProverCreateMasterSecretAsync(proverWallet, null); //8. Issuer Creates Credential Offer var credOffer = await AnonCreds.IssuerCreateCredentialOfferAsync(issuerWallet, credDefId); //9. Prover Creates Credential Request var createCredReqResult = await AnonCreds.ProverCreateCredentialReqAsync(proverWallet, proverDid, credOffer, credDefJson, masterSecretId); var credReqJson = createCredReqResult.CredentialRequestJson; var credReqMetadataJson = createCredReqResult.CredentialRequestMetadataJson; //10. Issuer open Tails Reader var blobStorageReaderCfg = await BlobStorage.OpenReaderAsync("default", tailsWriterConfig); //11. Issuer create Credential var credValuesJson = "{\n" + " \"sex\": {\"raw\": \"male\", \"encoded\": \"594465709955896723921094925839488742869205008160769251991705001\"},\n" + " \"name\": {\"raw\": \"Alex\", \"encoded\": \"1139481716457488690172217916278103335\"},\n" + " \"height\": {\"raw\": \"175\", \"encoded\": \"175\"},\n" + " \"age\": {\"raw\": \"28\", \"encoded\": \"28\"}\n" + " }"; var createCredentialResult = await AnonCreds.IssuerCreateCredentialAsync(issuerWallet, credOffer, credReqJson, credValuesJson, revRegId, blobStorageReaderCfg); var credential = createCredentialResult.CredentialJson; var revRegDeltaJson = createCredentialResult.RevocRegDeltaJson; var credRevId = createCredentialResult.RevocId; //12. Prover Stores Credential await AnonCreds.ProverStoreCredentialAsync(proverWallet, null, credReqMetadataJson, credential, credDefJson, revRegDefJson); //13. Prover Gets Credentials for Proof Request var proofRequestJson = "{\n" + " \"nonce\":\"123432421212\",\n" + " \"name\":\"proof_req_1\",\n" + " \"version\":\"0.1\", " + " \"requested_attributes\":{" + " \"attr1_referent\":{\"name\":\"name\"}" + " },\n" + " \"requested_predicates\":{" + " \"predicate1_referent\":{\"name\":\"age\",\"p_type\":\">=\",\"p_value\":18}" + " }" + " }"; var credentialsForProofJson = await AnonCreds.ProverGetCredentialsForProofReqAsync(proverWallet, proofRequestJson); var credentials = JObject.Parse(credentialsForProofJson); var credentialsForAttr1 = (JArray)credentials["attrs"]["attr1_referent"]; var credentialsForPredicate1 = (JArray)credentials["predicates"]["predicate1_referent"]; var credIdForAttr1 = credentialsForAttr1[0]["cred_info"]["referent"].ToObject <string>(); var credIdForPred1 = credentialsForPredicate1[0]["cred_info"]["referent"].ToObject <string>(); //14. Prover create RevocationState long timestamp = 100; var revStateJson = await AnonCreds.CreateRevocationStateAsync(blobStorageReaderCfg, revRegDefJson, revRegDeltaJson, timestamp, credRevId); //15. Prover Creates Proof var requestedCredentialsJson = string.Format("{{" + "\"self_attested_attributes\":{{}}," + "\"requested_attributes\":{{\"attr1_referent\":{{\"cred_id\":\"{0}\", \"revealed\":true, \"timestamp\":{1} }}}}," + "\"requested_predicates\":{{\"predicate1_referent\":{{\"cred_id\":\"{2}\", \"timestamp\":{3}}}}}" + "}}", credIdForAttr1, timestamp, credIdForPred1, timestamp); var schemas = string.Format("{{\"{0}\":{1}}}", schemaId, schemaJson); var credentialDefs = string.Format("{{\"{0}\":{1}}}", credDefId, credDefJson); var revStates = string.Format("{{\"{0}\": {{ \"{1}\":{2} }}}}", revRegId, timestamp, revStateJson); var proofJson = await AnonCreds.ProverCreateProofAsync(proverWallet, proofRequestJson, requestedCredentialsJson, masterSecretId, schemas, credentialDefs, revStates); var proof = JObject.Parse(proofJson); //16. Verifier verify Proof var revealedAttr1 = proof["requested_proof"]["revealed_attrs"]["attr1_referent"]; Debug.Assert("Alex" == revealedAttr1["raw"].ToObject <string>()); var revRegDefs = string.Format("{{\"{0}\":{1}}}", revRegId, revRegDefJson); var revRegs = string.Format("{{\"{0}\": {{ \"{1}\":{2} }}}}", revRegId, timestamp, revRegDeltaJson); var valid = await AnonCreds.VerifierVerifyProofAsync(proofRequestJson, proofJson, schemas, credentialDefs, revRegDefs, revRegs); Debug.Assert(valid); await issuerWallet.CloseAsync(); await proverWallet.CloseAsync(); await pool.CloseAsync(); } } finally { //17. Delete wallets and Pool ledger config await WalletUtils.DeleteWalletAsync(issuerWalletName, issuerWalletCredentials); await WalletUtils.DeleteWalletAsync(proverWalletName, proverWalletCredentials); await PoolUtils.DeletePoolLedgerConfigAsync(PoolUtils.DEFAULT_POOL_NAME); } Console.WriteLine("Anoncreds Revocation sample -> completed"); }
public async Task TestCreateWalletWorksForEmptyType() { var config = JsonConvert.SerializeObject(new { id = WalletUtils.GetWalletId() }); await Wallet.CreateWalletAsync(config, WALLET_CREDENTIALS); }
public static async Task Execute() { Console.WriteLine("Ledger sample -> started"); var myWalletName = "myWallet"; var theirWalletName = "theirWallet"; var trusteeSeed = "000000000000000000000000Trustee1"; try { // 1. Create ledger config from genesis txn file await PoolUtils.CreatePoolLedgerConfig(); // 2. Create and Open My Wallet await WalletUtils.CreateWalletAsync(PoolUtils.DEFAULT_POOL_NAME, myWalletName, "default", null, null); // 3. Create and Open Trustee Wallet await WalletUtils.CreateWalletAsync(PoolUtils.DEFAULT_POOL_NAME, theirWalletName, "default", null, null); //4. Open pool and wallets in using statements to ensure they are closed when finished. using (var pool = await Pool.OpenPoolLedgerAsync(PoolUtils.DEFAULT_POOL_NAME, "{}")) using (var myWallet = await Wallet.OpenWalletAsync(myWalletName, null, null)) using (var trusteeWallet = await Wallet.OpenWalletAsync(theirWalletName, null, null)) { //5. Create My Did var createMyDidResult = await Did.CreateAndStoreMyDidAsync(myWallet, "{}"); var myDid = createMyDidResult.Did; var myVerkey = createMyDidResult.VerKey; //6. Create Did from Trustee1 seed var theirDidJson = string.Format("{{\"seed\":\"{0}\"}}", trusteeSeed); var createTheirDidResult = await Did.CreateAndStoreMyDidAsync(trusteeWallet, theirDidJson); var trusteeDid = createTheirDidResult.Did; //7. Build Nym Request var nymRequest = await Ledger.BuildNymRequestAsync(trusteeDid, myDid, myVerkey, null, null); //8. Trustee Sign Nym Request var nymResponseJson = await Ledger.SignAndSubmitRequestAsync(pool, trusteeWallet, trusteeDid, nymRequest); var nymResponse = JObject.Parse(nymResponseJson); Debug.Assert(string.Equals(myDid, nymResponse["result"].Value <string>("dest"))); Debug.Assert(string.Equals(myVerkey, nymResponse["result"].Value <string>("verkey"))); //9. Close wallets and pool await myWallet.CloseAsync(); await trusteeWallet.CloseAsync(); await pool.CloseAsync(); } } finally { //10. Delete wallets and Pool ledger config await WalletUtils.DeleteWalletAsync(myWalletName, null); await WalletUtils.DeleteWalletAsync(theirWalletName, null); await PoolUtils.DeletePoolLedgerConfigAsync(PoolUtils.DEFAULT_POOL_NAME); } Console.WriteLine("Ledger sample -> completed"); }