Blockchains.razor 22 KB

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