Blockchains.razor 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. @page "/blockchains"
  2. @page "/blockchains/{Smart}"
  3. @using System.Text.RegularExpressions;
  4. @using Console = HyperCube.Utils.AdvConsole;
  5. @inject NavigationManager NavigationManager
  6. @inject IJSRuntime JsRuntime
  7. @using HyperCube.Models
  8. @using Microsoft.AspNetCore.Identity;
  9. @inject AuthenticationStateProvider AuthenticationStateProvider
  10. @inject UserManager<IdentityUser> UserManager
  11. @using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage;
  12. @inject ProtectedSessionStorage storage
  13. @attribute [Authorize]
  14. @code
  15. {
  16. string hidecontr = "visible";
  17. string hidereceipt = "hidden";
  18. string result = "";
  19. string qrr = "";
  20. string newcode = "";
  21. string newname = "";
  22. string balance = "";
  23. string sha3 = "";
  24. string function1 = "";
  25. string function_processed = "";
  26. string contractAddDisabled = "";
  27. string tokenContract = Blockchain.QNMAddress;
  28. string tokenName
  29. {
  30. get { return Blockchain.tokenName; }
  31. set { }
  32. }
  33. string tokenSymbol
  34. {
  35. get { return Blockchain.symbol; }
  36. set { }
  37. }
  38. string tokenDecimals
  39. {
  40. get { return Blockchain.decimals; }
  41. set { }
  42. }
  43. string tokenBalance
  44. {
  45. get { return Blockchain.tokenBalance; }
  46. set { }
  47. }
  48. string tokenAmount;
  49. string addressTo;
  50. string tid;
  51. SmartContract ctrSelected = new SmartContract();
  52. int ct;
  53. //ffff ffff ffff ffff ffff ffff ffff ffff ffff ffff ffff ffff ffff ffff ffff fff7
  54. string accountSelected;
  55. int contrtest
  56. {
  57. get
  58. {
  59. return ct;
  60. }
  61. set
  62. {
  63. ct = value;
  64. Console.WriteLine("ch contrtest val " + value);
  65. var ctr = GetContract(value);
  66. if (ctr != null)
  67. {
  68. Console.WriteLine("ctr found " + ctr.Name);
  69. ctrSelected = ctr;
  70. }
  71. }
  72. }
  73. }
  74. @if (Blockchain.blockChainsInitialized)
  75. {
  76. <select @bind="account.blockchain_selected" style="color:green; width:30%; margin:20px; margin-left:0px">
  77. <option value=0>Ethereum Dev Network</option>
  78. <option value=1>Ethereum Test Network</option>
  79. </select>
  80. <p><b>@bcMain.url:@bcMain.port </b><br /> <b>Address:</b> @bcMain.address<br /> <b>Balance:</b> @bcMain.balance</p>
  81. <br>
  82. @*<p style="visibility:@hidecontr">
  83. Add smart contract:
  84. <p><input id="newname" @bind="newname" placeholder="Имя нового контракта" /></p>
  85. <p><input id="newcode" size="100" @bind="newcode" name="code" type="text" placeholder="Исходный код" /></p>
  86. <p><input id="bytecode" size="100" @bind="bytecode" name="bytecode" type="text" placeholder="Байткод" @bind:event="oninput" /></p>
  87. <p><input id="function1" size="100" @bind="function1" name="function1" type="text" placeholder="Функция №1 - Объявление" /></p>
  88. <p><input disabled id="function_processed" size="100" @bind="function_processed" name="function_processed" type="text" placeholder="Функция" /></p>
  89. <button @onclick="checkCode">checkCode</button>
  90. <div style="visibility: @contractAddDisabled">
  91. <button @onclick="AddContract">Add</button>
  92. </div>
  93. <p><input id="getsha3" size="100" @bind="sha3" name="getsha3" type="text" placeholder="SHA3" @bind:event="oninput" /></p>
  94. <button @onclick="GetSHA3_2">GetSHA3</button>
  95. <br />
  96. </p>
  97. <div>
  98. <button @onclick="ImportERC20">ImportERC20</button>
  99. <p><input id="tc" size="100" @bind="tokenContract" name="code" type="text" placeholder="Адрес контракта токена" /></p>
  100. <p><input id="tn" size="100" @bind="tokenName" name="code" type="text" placeholder="" /></p>
  101. <p><input id="ts" size="100" @bind="tokenSymbol" name="code" type="text" placeholder="" /></p>
  102. <p><input id="td" size="100" @bind="tokenDecimals" name="code" type="text" placeholder="" /></p>
  103. <p><input id="tb" size="100" @bind="tokenBalance" name="code" type="text" placeholder="" /></p>
  104. </div>*@
  105. <div>
  106. <button @onclick="TransferToken">Transfer</button>
  107. <p><input id="tc" size="100" @bind="tokenContract" name="code" type="text" placeholder="Адрес контракта токена" /></p>
  108. <p><input id="tc" size="100" @bind="tokenAmount" name="code" type="text" placeholder="Количество" /></p>
  109. <p><input id="tn" size="100" @bind="addressTo" name="code" type="text" placeholder="Адрес получателя" /></p>
  110. </div>
  111. @*<div>
  112. <button @onclick="Transactions">Transactions</button>
  113. <button @onclick="COMulti">COMulti</button>
  114. </div>
  115. <div>
  116. <p><input id="tn" size="100" @bind="tid" name="code" type="text" placeholder="Адрес транзакции" /></p>
  117. </div>*@
  118. @*<p>
  119. <select @bind="contrtest">
  120. <option value="0">[Select Contract]</option>
  121. @if (Blockchain.loaded.Count > 0)
  122. {
  123. result = Blockchain.loaded.Count.ToString();
  124. if (bcMain.contracts.Count > 0)
  125. {
  126. @foreach (var c in bcMain.contracts.Values)
  127. {
  128. <option value="@c.ID">
  129. [@c.ID] @c.Name [@c.Address]
  130. </option>
  131. }
  132. }
  133. }
  134. </select>
  135. <button @onclick="deleteContract">Удалить контракт</button>
  136. <p>
  137. @ctrSelected.Code
  138. </p>
  139. @ctrSelected.Name
  140. <br>
  141. @bcMain.id;
  142. <br />
  143. </p>*@
  144. <p>
  145. <select @bind="accountSelected">
  146. <option value="0">[Select Account]</option>
  147. @if (Blockchain.loaded.Count > 0)
  148. {
  149. @foreach (var acc in AccountModel.Loaded.Values)
  150. {
  151. <option value="@acc.UUID">
  152. [@acc.Email] @acc.Name
  153. </option>
  154. }
  155. }
  156. </select>
  157. <button @onclick="GetBalance">GetBalance</button> Balance: @balance
  158. <button @onclick="Transfer50">Transfer 50</button>
  159. <button @onclick="Unlock">Unlock</button>
  160. <div>Wallet:@myWallet</div>
  161. <div>Token balance:@balanceToken</div>
  162. <br><br>
  163. @*<button @onclick="EstimateGas">EstimateGas</button>*@
  164. <p>Export address:</p>
  165. <button id="btn" @onclick="DloadJSON">Download JSON file</button>
  166. <button id="btn" @onclick="ExportPrivateKey">Private Key</button>
  167. <button id="btn" @onclick="PrivateKeyQR">QR code</button>
  168. <button id="btn" @onclick="Mint1000">Mint 1000</button>
  169. </p>
  170. <br>
  171. <br>
  172. <div>@((MarkupString)qrr)</div>
  173. @*<p>Result: @result, gas: @gas</p>*@
  174. }
  175. @code
  176. {
  177. Blockchain bcMain;
  178. AccountModel account;
  179. private Random r = new Random();
  180. private string bcURL = Blockchain.URLdefault;
  181. private int bcport = Blockchain.defaultPort;
  182. private string bytecode = "";
  183. private string error = "";
  184. string lastTransAddr = "";
  185. string contractAddress = "";
  186. string gas = "";
  187. async Task COMulti()
  188. {
  189. await bcMain.ChangeOwnerMulti();
  190. }
  191. async Task Transactions()
  192. {
  193. //bcMain.Transactions("0x862A2Ac8D1dB37085c786981A8F5bd54594f7162");
  194. //await bcMain.SubmitTransaction("0xD3ae749f1253b320ea2b90dc235ed72c80447AFF", 144, "0xe5D682717955d6C35d465A3485625C64655a04f4");
  195. var t1hash = await bcMain.GetTByHash(tid);
  196. }
  197. async Task<string> Mint1000()
  198. {
  199. var acc = AccountModel.Find(accountSelected);
  200. var bc = bcMain;
  201. var addr = await acc.GetOrCreateActualAddress(bc);
  202. await bcMain.Mint(tokenAmount, addr);
  203. return "";
  204. }
  205. async Task<string> PrivateKeyQR()
  206. {
  207. var code = await ExportPrivateKey();
  208. code = HyperCube.Models.Blockchain.QRtest(code);
  209. qrr = $"<img src=\"data: image / png; base64, {code}\"/>";
  210. return "";
  211. }
  212. async Task<string> ExportPrivateKey()
  213. {
  214. var wallet = await GetWallet();
  215. if (wallet != null)
  216. {
  217. var acc = AccountModel.Find(accountSelected);
  218. string text = getFiles(wallet, "key", acc.PWDHash);
  219. qrr = $"<p>{text}</p>";
  220. return text;
  221. //return await JsRuntime.InvokeAsync<string>("test", text);
  222. }
  223. return "";
  224. }
  225. async Task<string> DloadJSON()
  226. {
  227. var wallet = await GetWallet();
  228. if (wallet != null)
  229. {
  230. string text = getFiles(wallet, "json");
  231. qrr = $"<p>{text}</p>";
  232. return await JsRuntime.InvokeAsync<string>("test", text);
  233. }
  234. return "";
  235. }
  236. async Task<string> GetWallet()
  237. {
  238. if (accountSelected != "" && accountSelected != null && accountSelected != "0")
  239. {
  240. var acc = AccountModel.Find(accountSelected);
  241. if (acc != null)
  242. {
  243. myWallet = await acc.GetOrCreateActualAddress(bcMain);
  244. return myWallet;
  245. }
  246. }
  247. return null;
  248. }
  249. //web3.personal.importRawKey("private key", "password")
  250. //Verify
  251. //function verify( address payable verifier, address payable initiator, uint8 article_value, uint8 verify_complexity)
  252. //0x608060405234801561001057600080fd5b50610190806100206000396000f3fe60806040526004361061001e5760003560e01c8063619837de14610023575b600080fd5b61009f6004803603608081101561003957600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803560ff169060200190929190803560ff1690602001909291905050506100a1565b005b600060058302820160ff1690508063ffffffff164710610153578473ffffffffffffffffffffffffffffffffffffffff166108fc8360ff169081150290604051600060405180830381858888f19350505050158015610104573d6000803e3d6000fd5b508373ffffffffffffffffffffffffffffffffffffffff166108fc6005850260ff169081150290604051600060405180830381858888f19350505050158015610151573d6000803e3d6000fd5b505b505050505056fea2646970667358221220847188fccb79ed4087ece85f7a8d9c3eaf187342166d7a66131b00a13bb0577b64736f6c63430007040033
  253. async Task<string> Unlock()
  254. {
  255. var bc = bcMain;
  256. //var ret = await bc.RunFunction("personal_unlockAccount", $"\"{bc.address}\",\"test_Password_212\",0");
  257. var acc = AccountModel.Find(accountSelected);
  258. var wallet = await GetWallet();
  259. var ret = await bc.RunFunction("personal_unlockAccount", $"\"{wallet}\",\"{acc.PWDHash}\",0");
  260. //address, passphrase, duration
  261. //{ "method": "personal_unlockAccount", "params": [string, string, number]}
  262. return ret;
  263. }
  264. async Task ImportERC20()
  265. {
  266. await bcMain.ImportERC20(tokenContract, myWallet);
  267. //await Blockchain.GetMain().ImportERC20("0x413D9500A675d9b645034aC5f4325BF12ddeb7c1");
  268. }
  269. async Task TransferToken()
  270. {
  271. await bcMain.TransferToken(Blockchain.MultiOwnerContractRinkeby, tokenContract, addressTo, tokenAmount);
  272. }
  273. async Task EstimateGas()
  274. {
  275. gas = await bcMain.GetEstimatedGasContractAdd(ctrSelected.ByteCode);
  276. }
  277. async Task deleteContract()
  278. {
  279. var main = bcMain;
  280. if (main != null)
  281. {
  282. main.contracts.Remove(ctrSelected.ID);
  283. main.contractNames.Remove(ctrSelected.Name);
  284. MySQLConnector.Instance().SQLInsert($"delete from smart_contracts where id ={ctrSelected.ID}");
  285. MySQLConnector.Instance().SQLInsert($"delete from functions where contract_id ={ctrSelected.ID}");
  286. ctrSelected = null;
  287. }
  288. }
  289. async Task checkCode()
  290. {
  291. ////string pattern = @"function\s+(\S+)\s*\((.*)\)\s*{.*}";
  292. //string pattern = @"function\s+(\S+)\s*\((.*)\).*";
  293. //string replacement_name = "$1";
  294. //string replacement_params = "$2";
  295. //string input = function1;
  296. //string resultname = Regex.Replace(input, pattern, replacement_name).Trim();
  297. //string param_pattern = @"(uint8|address)";
  298. //var final = resultname + "(";
  299. //if (input != resultname)
  300. //{
  301. // //function_processed += "name " + resultname + " ";
  302. // string resultparams = Regex.Replace(input, pattern, replacement_params).Trim();
  303. // if (input != resultparams)
  304. // {
  305. // //function_processed += "params " + resultparams+" matches: ";
  306. // int i = 0;
  307. // foreach (Match match in Regex.Matches(resultparams, param_pattern))
  308. // {
  309. // if (i > 0)
  310. // final += "," + match.Value;
  311. // else
  312. // final += match.Value;
  313. // i++;
  314. // }
  315. // }
  316. //}
  317. //function_processed = final + ")";
  318. //sha3 = await GetSHA3(function_processed);
  319. //getFiles();
  320. function_processed = await bcMain.compileFunction(function1, false);
  321. if (function1 != "()" && function1 != "")
  322. contractAddDisabled = "";
  323. else
  324. contractAddDisabled = "visible";
  325. }
  326. async Task<string> GetSHA3(string code)
  327. {
  328. var res = await bcMain.GetSHA3(code);
  329. Console.WriteLine($"GetSHA3 {code} {res}");
  330. var ret = res.Substring(2, 8);
  331. return ret;
  332. }
  333. async Task<string> GetSHA3_2()
  334. {
  335. var res = await bcMain.GetSHA3(sha3);
  336. Console.WriteLine($"GetSHA3 {res}");
  337. var ret = res.Substring(2, 8);
  338. return ret;
  339. }
  340. //protected async Task TransferContract()
  341. //{
  342. // var ttt = "123";
  343. // Console.WriteLine($"len {ttt.Length}");
  344. // try
  345. // {
  346. // var myacc = AccountModel.Current;
  347. // Console.WriteLine($"TransferContract run");
  348. // Console.WriteLine($"TransferContract {myacc.Name}");
  349. // var recipient = AccountModel.Find(accountSelected);
  350. // if (recipient != null)
  351. // {
  352. // var bc = Blockchain.GetMain();
  353. // //var b2h = Blockchain.bin2hex("getCount()");
  354. // //Console.WriteLine("bin2hex " + b2h);
  355. // var part1 = await Blockchain.GetSHA3("myTransfer(address)");
  356. // //var part2 = await Blockchain.GetSHA3(recipient.eth_address);
  357. // var zerofill = Blockchain.zerofill(part1.Substring(0, 10), 32, true);
  358. // //var zerofill2 = Blockchain.zerofill(part2, 32, true);
  359. // var radr = await recipient.GetOrCreateActualAddress(bc);
  360. // var paramstring = "0x" + zerofill + radr.Remove(0, 2);
  361. // Console.WriteLine($"paramstring {paramstring}");
  362. // //todo pack myTransfer(address)
  363. // //todo pack contr.Address
  364. // if (bc.contractNames.ContainsKey("Transfer"))
  365. // {
  366. // var contr = bc.contractNames["Transfer"];
  367. // var res = await bc.RunContractWrite(contr.Address, $"{paramstring}");
  368. // Console.WriteLine("TransferContract result " + res);
  369. // var receipt = await bc.GetReceipt(res);
  370. // Console.WriteLine("TransferContract receipt " + receipt);
  371. // }
  372. // }
  373. // //TODO run smart contract with verifier wallet
  374. // }
  375. // catch (Exception e)
  376. // {
  377. // Console.WriteLine(e.Message);
  378. // }
  379. //}
  380. private async Task Transfer50()
  381. {
  382. var acc = AccountModel.Find(accountSelected);
  383. var bc = bcMain;
  384. var addr = await acc.GetOrCreateActualAddress(bc);
  385. var res = await bc.SendTransaction(bcMain.address, addr, 50);
  386. }
  387. private async Task GetBalance()
  388. {
  389. Console.WriteLine("accountSelected " + accountSelected);
  390. if (accountSelected != "" && accountSelected != null && accountSelected != "0")
  391. {
  392. var acc = AccountModel.Find(accountSelected);
  393. if (acc != null)
  394. {
  395. myWallet = await acc.GetOrCreateActualAddress(bcMain);
  396. balance = await acc.GetBalance();
  397. }
  398. }
  399. else
  400. {
  401. myWallet = bcMain.address;
  402. balance = await bcMain.GetBalance();
  403. }
  404. await bcMain.GetBalanceToken(Blockchain.QNMAddress, myWallet);
  405. }
  406. //private async Task CreateBlockchainAccount(Blockchain bc, string pass)
  407. //{
  408. // AccountModel account = AccountModel.Find(accountSelected);
  409. // if (account != null)
  410. // {
  411. // var res = await bc.CreateBlockchainAccount(account, pass);
  412. // }
  413. //}
  414. private async Task ChangeContract()
  415. {
  416. Console.WriteLine("ChangeContract " + contrtest);
  417. //TODO result as transaction addr
  418. //result = await Blockchain.loaded[0].GetReceipt(result);
  419. }
  420. private async Task RunContract()
  421. {
  422. //TODO result as transaction addr
  423. }
  424. private async Task AddContract()
  425. {
  426. if (Blockchain.loaded.Count > 0)
  427. {
  428. var taddr = await bcMain.AddContract(newname, newcode, bytecode);
  429. if (taddr.Length > 0 && taddr[0] != "")
  430. {
  431. result = taddr[0].ToString();
  432. //hidereceipt = "visible";
  433. var caddr = await bcMain.GetReceipt(result, true);
  434. if (caddr != "")
  435. {
  436. result = "contractAddress: " + caddr;
  437. contractAddress = caddr;
  438. //var id = (int) taddr[1];
  439. var smc = taddr[1] as SmartContract;//Blockchain.GetMain().contracts[id];
  440. smc.Address = contractAddress;
  441. MySQLConnector.Instance().SQLInsert($"update smart_contracts set address='{contractAddress}' where id= {smc.ID}");
  442. //var run = await Blockchain.GetMain().RunContractWrite(contractAddress, "0x11111111");
  443. //result = "run: " + run;
  444. smc.AddFunction(function_processed, sha3);
  445. }
  446. }
  447. }
  448. //private Post post = new Post();
  449. }
  450. SmartContract GetContract(int id)
  451. {
  452. if (bcMain != null)
  453. {
  454. if (bcMain.contracts.ContainsKey(id))
  455. return bcMain.contracts[id];
  456. }
  457. return null;
  458. }
  459. protected override async Task OnInitializedAsync()
  460. {
  461. //Console.WriteLine($"Blazor is {Smart}");
  462. Console.WriteLine($"Blockchains OnInitializedAsync");
  463. //account = AppData.CurrentAccount;
  464. //var res = await storage.GetAsync<AccountModel>("acc");
  465. account = await GetCurrentAcc();
  466. //Console.WriteLine($"myFlag {myFlag.Value.Name}");
  467. Console.WriteLine($"Blockchains account {account}");
  468. bcMain = await account.GetSelectedBlockChain();
  469. Console.WriteLine($"Blockchains OnInitializedAsync {bcMain}");
  470. await GetBalance();
  471. }
  472. private async Task<AccountModel> GetCurrentAcc()
  473. {
  474. AccountModel account = new();
  475. var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
  476. var user = authState.User;
  477. if (user.Identity.IsAuthenticated)
  478. {
  479. var currentUser = await UserManager.GetUserAsync(user);
  480. account.UUID = currentUser.Id;
  481. //account.Name = currentUser.UserName;
  482. //account.Email = currentUser.Email;
  483. var acc = AccountModel.Find(account.UUID);
  484. if (acc != null)
  485. account = acc;
  486. ///tmp
  487. //account.AccRole = Role.User;
  488. return account;
  489. }
  490. return null;
  491. }
  492. //private async Task GetBlockChain()
  493. //{
  494. // //if (Blockchain.loaded.Count == 0)
  495. // //{
  496. // Blockchain bc = new HyperCube.Models.Blockchain(bcURL, bcport);
  497. // result = await bc.Initialize();
  498. // if (result != "")
  499. // hidecontr = "visible";
  500. // //bcURL = bc.GetAddress();
  501. // //bc.ExecuteContract();
  502. // //bcURL = bc.address;
  503. // //hidecontr = "hidden";
  504. // //}
  505. // //private Post post = new Post();
  506. //}
  507. }