private static void GetWithdrawQuota() { var walletClient = new WalletClient(Config.AccessKey, Config.SecretKey); var request = new GetRequest() .AddParam("currency", "btc"); var result = walletClient.GetWithdrawQuotaAsync(request).Result; if (result != null && result.data != null && result.data.chains != null) { foreach (var c in result.data.chains) { Console.WriteLine($"chain: {c.chain}, max withdraw amount {c.maxWithdrawAmt}, total quota {c.withdrawQuotaTotal}"); } } }
private static void GetDepoistAddress() { var walletClient = new WalletClient(Config.AccessKey, Config.SecretKey); var request = new GetRequest() .AddParam("currency", "btc"); var result = walletClient.GetDepositAddressAsync(request).Result; if (result != null && result.data != null) { foreach (var a in result.data) { Console.WriteLine($"currency: {a.currency}, addr: {a.address}, chain: {a.chain}"); } Console.WriteLine($"There are total {result.data.Length} addresses"); } }
private static void GetDepositWithdrawHistory() { var walletClient = new WalletClient(Config.AccessKey, Config.SecretKey); var request = new GetRequest() .AddParam("type", "deposit"); var result = walletClient.GetDepositWithdrawHistoryAsync(request).Result; if (result != null && result.data != null) { foreach (var h in result.data) { Console.WriteLine($"type: {h.type}, currency: {h.currency}, amount: {h.amount}, updatedAt: {h.updatedAt}"); } Console.WriteLine($"There are {result.data.Length} deposit and withdraw history"); } }
public MainWindowViewModel(Window desktopMainWindow, SprdSettings sprdSettings) { _desktopMainWindow = desktopMainWindow; _sprdSettings = sprdSettings; _sprdSelection = new SprdSelection { Pool = new StakePool { Name = "<Select Pool>" }, Wallet = new Wallet { Name = "<Select Wallet>" }, }; SpreadAdaCommand = ReactiveCommand.Create(SpreadAda);//, this.WhenAnyValue(x => x.CanExecuteSprd)); BlockChainCache = new BlockChainCache { StakePools = new ObservableCollection <StakePool>() }; var stakePoolDbFileInfo = new FileInfo(_stakePoolListDatabase); if (stakePoolDbFileInfo.Exists) { var jsonCacheStakePools = File.ReadAllBytes(_stakePoolListDatabase); var readOnlySpan = new ReadOnlySpan <byte>(jsonCacheStakePools); BlockChainCache = JsonSerializer.Deserialize <BlockChainCache>(readOnlySpan); _allStakePools = BlockChainCache.StakePools; OnPropertyChanged("BlockChainCache"); } else { _allStakePools = new ObservableCollection <StakePool>(); } _allWallets = new ObservableCollection <Wallet>(); LastComittedAdaPools = new ObservableCollection <SprdPoolInfo>(); _cardanoServer = new CardanoServer(); _sprdServer = new SprdServer(); _walletClient = new WalletClient(_sprdSettings.WalletSettings.Port, _sprdServer); desktopMainWindow.Opened += StartCardanoServer; desktopMainWindow.Closing += WindowClosing; }
public HttpKeyRingMonitor(string baseAddress, KeyRing keyRing, int addressCount) : base(baseAddress, keyRing.Network) { AssertNetwork(keyRing.Network); AddressCount = addressCount; BaseKeyRing = keyRing; KeyRing = new HttpKeyRing(this); _periodicUpdate = new PeriodicUpdate(() => { if (_syncProgressPercent == 100) { UpdateKeyRingHistoryAndBalanceInfo(); } }); _qBitNinjaWalletClient = Client.GetWalletClient(QBitNinjaWalletName); _qBitNinjaWalletClient.CreateIfNotExists().Wait(); StartInitializingQBitNinjaWallet(); }
private static void GetDepoistAddress() { var walletClient = new WalletClient(Config.AccessKey, Config.SecretKey); _logger.Start(); var request = new GetRequest() .AddParam("currency", "btc"); var result = walletClient.GetDepositAddressAsync(request).Result; _logger.StopAndLog(); if (result != null && result.data != null) { AppLogger.Info($"Get deposit address, id={result.data.Length}"); foreach (var a in result.data) { AppLogger.Info($"currency: {a.currency}, addr: {a.address}, chain: {a.chain}"); } } }
private static void GetSubUserDepositHistory() { var walletClient = new WalletClient(Config.AccessKey, Config.SecretKey); _logger.Start(); var request = new GetRequest() .AddParam("subUid", Config.SubUserId); var result = walletClient.GetSubUserDepositHistoryAsync(request).Result; _logger.StopAndLog(); if (result != null && result.data != null) { AppLogger.Info($"Get sub user deposit history, count={result.data.Length}"); foreach (var h in result.data) { AppLogger.Info($"Deposit history, id={h.id}, currency={h.currency}, amount={h.amount}, address={h.address}, updatedAt={h.updateTime}"); } } }
public NinjaInteractor() { /* * 1.Choose a transaction at random on https://blockchain.info * 2.Download all information available for this transaction from your code * 3.Download all information relative to your CoPay address from your code * 4.Print in the console the balance and the list of transactions related to this address * 5.Print the list of unspent transaction outputs, also known as UTXO or coins * 6.Explain the relationship between the balance and the UTXO set */ //1 + 2 Transaction_info(); QBitNinjaClient client = new QBitNinjaClient(Network.TestNet); //3 WalletClient wallet = CreateWallet(client); //4 Copay_info(client, wallet); //5 PrintUTXO(client, wallet); }
private static void CancelWithdrawCurrency() { var walletClient = new WalletClient(Config.AccessKey, Config.SecretKey); var result = walletClient.CancelWithdrawCurrencyAsync(1).Result; if (result != null) { switch (result.status) { case "ok": { Console.WriteLine($"Cancel withdraw successfully, transfer id: {result.data}"); break; } case "error": { Console.WriteLine($"Cancel withdraw fail, error code: {result.errorCode}, error message: {result.errorMessage}"); break; } } } }
private void Application_Startup(object sender, StartupEventArgs e) { // WPF defaults to using the en-US culture for all formatted bindings. // Override this with the system's current culture. FrameworkElement.LanguageProperty.OverrideMetadata(typeof(FrameworkElement), new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag))); var args = ProcessArguments.ParseArguments(e.Args); var activeNetwork = args.IntendedNetwork; WalletClient.Initialize(); Directory.CreateDirectory(AppDataDir); // try to obtain some default rpc settings to autofill the startup dialogs with. // try paymetheus defaults first, and if that fails, look for a dcrd config. try { var iniParser = new FileIniDataParser(); IniData config = null; string defaultsFile = Path.Combine(AppDataDir, "defaults.ini"); if (File.Exists(defaultsFile)) { config = iniParser.ReadFile(defaultsFile); } else { var consensusRpcAppData = Portability.LocalAppData(Environment.OSVersion.Platform, "", ConsensusServerRpcOptions.ApplicationName); var consensusRpcConfig = ConsensusServerRpcOptions.ApplicationName + ".conf"; var consensusConfigFilePath = Path.Combine(consensusRpcAppData, consensusRpcConfig); if (File.Exists(consensusConfigFilePath)) { config = iniParser.ReadFile(consensusConfigFilePath); } } if (config != null) { // Settings can be found in either the Application Options or global sections. var section = config["Application Options"]; if (section == null) { section = config.Global; } var rpcUser = section["rpcuser"] ?? ""; var rpcPass = section["rpcpass"] ?? ""; var rpcListen = section["rpclisten"] ?? ""; var rpcCert = section["rpccert"] ?? ""; // rpclisten and rpccert can be filled with sensible defaults when empty. user and password can not. if (rpcListen == "") { rpcListen = "127.0.0.1"; } if (rpcCert == "") { var localCertPath = ConsensusServerRpcOptions.LocalCertificateFilePath(); if (File.Exists(localCertPath)) { rpcCert = localCertPath; } } DefaultCSRPO = new ConsensusServerRpcOptions(rpcListen, rpcUser, rpcPass, rpcCert); } } catch { } // Ignore any errors, this will just result in leaving defaults empty. var syncTask = Task.Run(async() => { return(await SynchronizerViewModel.Startup(activeNetwork, AppDataDir, args.SearchPathForWalletProcess, args.ExtraWalletArgs)); }); var synchronizer = syncTask.Result; SingletonViewModelLocator.RegisterInstance("Synchronizer", synchronizer); ActiveNetwork = activeNetwork; Synchronizer = synchronizer; Current.Exit += Application_Exit; }
public async Task <PubKey> JoinFederationAsync(JoinFederationRequestModel request, CancellationToken cancellationToken) { // Get the address pub key hash. BitcoinAddress address = BitcoinAddress.Create(request.CollateralAddress, this.counterChainSettings.CounterChainNetwork); KeyId addressKey = PayToPubkeyHashTemplate.Instance.ExtractScriptPubKeyParameters(address.ScriptPubKey); // Get mining key. var keyTool = new KeyTool(this.nodeSettings.DataFolder); Key minerKey = keyTool.LoadPrivateKey(); if (minerKey == null) { throw new Exception($"The private key file ({KeyTool.KeyFileDefaultName}) has not been configured or is not present."); } var expectedCollateralAmount = CollateralFederationMember.GetCollateralAmountForPubKey(this.network, minerKey.PubKey); var collateralAmount = new Money(expectedCollateralAmount, MoneyUnit.BTC); var joinRequest = new JoinFederationRequest(minerKey.PubKey, collateralAmount, addressKey); // Populate the RemovalEventId. var collateralFederationMember = new CollateralFederationMember(minerKey.PubKey, false, joinRequest.CollateralAmount, request.CollateralAddress); byte[] federationMemberBytes = (this.network.Consensus.ConsensusFactory as CollateralPoAConsensusFactory).SerializeFederationMember(collateralFederationMember); Poll poll = this.votingManager.GetApprovedPolls().FirstOrDefault(x => x.IsExecuted && x.VotingData.Key == VoteKey.KickFederationMember && x.VotingData.Data.SequenceEqual(federationMemberBytes)); joinRequest.RemovalEventId = (poll == null) ? Guid.Empty : new Guid(poll.PollExecutedBlockData.Hash.ToBytes().TakeLast(16).ToArray()); // Get the signature by calling the counter-chain "signmessage" API. var signMessageRequest = new SignMessageRequest() { Message = joinRequest.SignatureMessage, WalletName = request.CollateralWalletName, Password = request.CollateralWalletPassword, ExternalAddress = request.CollateralAddress }; var walletClient = new WalletClient(this.loggerFactory, this.httpClientFactory, $"http://{this.counterChainSettings.CounterChainApiHost}", this.counterChainSettings.CounterChainApiPort); string signature = await walletClient.SignMessageAsync(signMessageRequest, cancellationToken); if (signature == null) { throw new Exception("The call to sign the join federation request failed. It could have timed-out or the counter chain node is offline."); } joinRequest.AddSignature(signature); IWalletTransactionHandler walletTransactionHandler = this.fullNode.NodeService <IWalletTransactionHandler>(); var encoder = new JoinFederationRequestEncoder(this.loggerFactory); JoinFederationRequestResult result = JoinFederationRequestBuilder.BuildTransaction(walletTransactionHandler, this.network, joinRequest, encoder, request.WalletName, request.WalletAccount, request.WalletPassword); if (result.Transaction == null) { throw new Exception(result.Errors); } IWalletService walletService = this.fullNode.NodeService <IWalletService>(); await walletService.SendTransaction(new SendTransactionRequest(result.Transaction.ToHex()), cancellationToken); return(minerKey.PubKey); }
public WalletsControllerTests(ServerFixture serverFixture) : base(serverFixture) { _walletClient = new WalletClient(serverFixture.Client); }
public WalletEventListener(WalletSettings settings) { _walletClient = new WalletClient(settings); _lastTransactionIds = new List <string>(); _coinName = settings.CoinName; }
public async Task <IActionResult> RequestTokens([FromRoute] string address, [FromServices] WalletClient walletClient, [FromServices] IOptions <Configuration.Token> tokenOptions) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (Client.WalletAddress.Decode58Check(address) == null) { return(NotFound()); } var result = new RequestTokensResult() { Result = RequestTokensResult.Type.MaximumReachedPerDay, TransactionHash = null, }; var ipAddress = HttpContext.Connection.RemoteIpAddress.ToString(); var receivedTokensToday = _context.UserReceivedTokens.Where(rt => (rt.Address == address || rt.Ip == ipAddress) && rt.CreatedAt.Date == DateTime.Today ).ToList(); var sumTokensReceivedToday = receivedTokensToday.Sum(rt => rt.ReceivedTokens); if (sumTokensReceivedToday < tokenOptions.Value.TransferMaxPerAccountEveryDay) { try { var userAccount = await walletClient.GetAddressInformation(address); var asset = userAccount.AssetV2.SingleOrDefault(a => a.Key.Equals(tokenOptions.Value.Id, StringComparison.CurrentCultureIgnoreCase)); if (asset.Key == null || asset.Value <= tokenOptions.Value.TransferOnlyWhenHasLessOrEqualThan) { var canReceiveToday = (tokenOptions.Value.TransferMaxPerAccountEveryDay - sumTokensReceivedToday); var amount = (canReceiveToday <= tokenOptions.Value.TransferSteps ? canReceiveToday : tokenOptions.Value.TransferSteps ); var transferResult = await walletClient.TransferTokenFromProperty(amount, address); if (transferResult.Result) { var transactionHash = Common.Utils .ToHexString(Crypto.Sha256.Hash(transferResult.Transaction.RawData.ToByteArray())) .ToLower(); result.TransactionHash = transactionHash; result.Result = RequestTokensResult.Type.Transferred; _context.UserReceivedTokens.Add(new UserReceivedToken() { Address = address, Ip = ipAddress, ReceivedTokens = amount, CreatedAt = DateTime.UtcNow, }); _context.SaveChanges(); } else { result.Result = RequestTokensResult.Type.ServerError; } } else { result.Result = RequestTokensResult.Type.HasEnough; } } catch (RpcException e) { result.Result = RequestTokensResult.Type.ServerError; _logger.LogError("Couldn't transfer tokens to {Receiver}! Error:", address); _logger.LogError(e.Message); _logger.LogError(e.StackTrace); } catch (DbUpdateException e) { _logger.LogError("Couldn't save the userReceivedToken in Database! Error:"); _logger.LogError(e.Message); _logger.LogError(e.StackTrace); } } return(Ok(result)); }
public async Task <PubKey> JoinFederationAsync(JoinFederationRequestModel request, CancellationToken cancellationToken) { // Wait until the node is synced before joining. if (this.initialBlockDownloadState.IsInitialBlockDownload()) { throw new Exception($"Please wait until the node is synced with the network before attempting to join the federation."); } // First ensure that this collateral address isnt already present in the federation. if (this.federationManager.GetFederationMembers().IsCollateralAddressRegistered(request.CollateralAddress)) { throw new Exception($"The provided collateral address '{request.CollateralAddress}' is already present in the federation."); } // Get the address pub key hash. BitcoinAddress address = BitcoinAddress.Create(request.CollateralAddress, this.counterChainSettings.CounterChainNetwork); KeyId addressKey = PayToPubkeyHashTemplate.Instance.ExtractScriptPubKeyParameters(address.ScriptPubKey); // Get mining key. var keyTool = new KeyTool(this.nodeSettings.DataFolder); Key minerKey = keyTool.LoadPrivateKey(); if (minerKey == null) { throw new Exception($"The private key file ({KeyTool.KeyFileDefaultName}) has not been configured or is not present."); } var expectedCollateralAmount = CollateralFederationMember.GetCollateralAmountForPubKey(this.network, minerKey.PubKey); var joinRequest = new JoinFederationRequest(minerKey.PubKey, new Money(expectedCollateralAmount, MoneyUnit.BTC), addressKey); // Populate the RemovalEventId. SetLastRemovalEventId(joinRequest, GetFederationMemberBytes(joinRequest, this.network, this.counterChainSettings.CounterChainNetwork), this.votingManager); // Get the signature by calling the counter-chain "signmessage" API. var signMessageRequest = new SignMessageRequest() { Message = joinRequest.SignatureMessage, WalletName = request.CollateralWalletName, Password = request.CollateralWalletPassword, ExternalAddress = request.CollateralAddress }; var walletClient = new WalletClient(this.httpClientFactory, $"http://{this.counterChainSettings.CounterChainApiHost}", this.counterChainSettings.CounterChainApiPort); try { string signature = await walletClient.SignMessageAsync(signMessageRequest, cancellationToken); joinRequest.AddSignature(signature); } catch (Exception err) { throw new Exception($"The call to sign the join federation request failed: '{err.Message}'."); } IWalletTransactionHandler walletTransactionHandler = this.fullNode.NodeService <IWalletTransactionHandler>(); var encoder = new JoinFederationRequestEncoder(); JoinFederationRequestResult result = JoinFederationRequestBuilder.BuildTransaction(walletTransactionHandler, this.network, joinRequest, encoder, request.WalletName, request.WalletAccount, request.WalletPassword); if (result.Transaction == null) { throw new Exception(result.Errors); } IWalletService walletService = this.fullNode.NodeService <IWalletService>(); await walletService.SendTransaction(new SendTransactionRequest(result.Transaction.ToHex()), cancellationToken); return(minerKey.PubKey); }