Blockchains.razor 20 KB

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