From 5affe69fe0b191cfe47ae3d9defcb887c2e48687 Mon Sep 17 00:00:00 2001 From: "progr76@gmail.com" Date: Sat, 16 Feb 2019 20:08:41 +0300 Subject: [PATCH] 0.886 --- Bin/Light/Tera-light.zip | Bin 120100 -> 120100 bytes Bin/Light/tera_light_setup.exe | Bin 705280 -> 705276 bytes Doc/Eng/API2.md | 80 ++++++++++++++++++++++----- Doc/Rus/API2.md | 74 +++++++++++++++++++++---- Source/core/base.js | 2 +- Source/core/block-loader.js | 4 +- Source/core/constant.js | 2 +- Source/core/db/block-db.js | 64 +++++++++++++++++---- Source/core/html-server.js | 2 +- Source/core/transaction-validator.js | 37 ++++++++++--- Source/core/wallet.js | 7 ++- Source/dapp/accounts.js | 15 ++++- Source/dapp/dapp.js | 2 +- Source/dapp/file.js | 2 +- Source/dapp/smart.js | 4 +- Source/process/api-exchange.js | 40 ++++++++++---- Source/process/main-process.js | 23 +++++++- Source/process/tx-process.js | 2 +- Source/process/web-process.js | 21 ++++++- 19 files changed, 304 insertions(+), 77 deletions(-) diff --git a/Bin/Light/Tera-light.zip b/Bin/Light/Tera-light.zip index a2d81b01ad5113bef8f08e61a4954a8d45fd7f0d..6203589b9de1ad7e7df41c98b57cdd6f6f84728d 100644 GIT binary patch delta 1144 zcmZ3oihao{cHRJQW)=|!1_llW)`bBZdELdC*%k(D4i^`eW9D2KFge#$o*5{yx!?3O zJ6IsrRt_vsXS<0J%rLf}tOjPBOufnkW-QFG=LRz#7n?yCGWCiOhC^2mM9ujg7FMvD zYZG_zgBg<-dMJPy_YS^O0W;1&%M=E?#`;&?To7aXp6QHS++fzpMT}n2byD+p~=3>Kjg<1N)wkV()W|7JLUkK@>ke2r_y4#B+>dpb(wD>Kvn;`ls~s zV3Qz{R~TK{#IU-N|2(6$y2@RM;x8{CZp5Xy@I0f1dRpZLu*oa}*5FV`55aEoh4YN| z>UO18>{s%I-PHhF)WLV-nWrt}pD3v5!0VbiB-_C#o W6_Q7$FT27R!8S7=>|U0uj0ym}y?ZeL delta 1144 zcma))ZAep57{~A9mJ8P=GTkginu>wN~C zrt({RKNJ2(6f(4^0s|1rLe+a0X86C(C(xx~S^nH-@DA^x=|QN_JKtV;Uo$2{`H10j z%^2MhgaA8ASA?K~xJTPRGSk$`Oc^$ard3aG$WUJgX?a41vKm29HbL7$u!ii&%tk2j z?I_f?jwa#c9%(cL<)n0!U%TlIPyQF4OD+z>YO?E;5t9?&g8MnkowpKW%q5=4>mVAY>D$No0$QRSr4PuduTQvE^yvJb2+leKuVKMF_C zG{&HWY>r#eoH@Wu8F~ZrU&H#>5(66<@*T(i{kp(m*U{X0OJ(px465`~jy8nzU*WZu zab+fEmX9kNFM7ev^=o;R9+*rilP-@#6=`lbfk_S97l&tAa?3FeC(8M}dVVr%$xd0R YP+=dhJufG{CPQO-v6kIJ)p4-=1|USVN&o-= diff --git a/Bin/Light/tera_light_setup.exe b/Bin/Light/tera_light_setup.exe index 81446ad3c4bc546b992bfa61cfe2d0b8e6d17fb1..0d84875b7038de984decb4db6709c72a694d92c3 100644 GIT binary patch delta 824 zcmV-81IPS;hAaGqD}b~C_}?7-!U_PO^8^3@FcJVbc;>?hO#=V`>;V9EgP*a76yO1e z6yO4f6yO856yOAm5DiU(IN|pK0005-e=LEQt?&dWe@%hWHE$EC`{&?#=UJ{;9-k8kF%L)ZltHL9Q2^h^?sW;(e?UGY&oLOutUCx z{9dsdf8Po8IVd&o)yOlZ-I0G!E8Z6P#!{niq;ix?Z|{*yxQ+T{qo~JAuPUuTMXCKW z8oVLaZktO5l$x9-cTdh%Uqh$E>&ZBRdnvv)xYZxZ7DZmvC%;@8=%0*f4{|hleR6oA zgBjHK_RKSyM0Y))xU&cFD3uy40j7&F@k~j_f0ALI92GQpJAuy~mNN0ZZzv=wCY1&N zp?c-^$0~D%Y1d;vv19{;bf9+Ya(=`3YW7#Rlo5k}qC8b$h9K^eg1F}~VAWd&_V$RJ zP83U7sNf~@;!+eum(I!)jCN_*T_IjfeXYDca71{rwPrGcXv;A0#8TK^dxqPi;C1*} ze}f@m0zLKlrcTUoe+Uob z2|Nu+Ojw_~pqMPJbVS3PH<@*m+))Uh2>)6-S}21nF9J#bNvZCbNV2`{a z_>LP|UZ5>Ot3mN+3va0C(vb;`)cuv@e-pBmtpB_}0J8@5RDILI)hqSfu|4Jgoq5n3 zTN$7S$qxRheQt`~J4VObe3px43-Q3z)*sqFtNg89@2KGH;HW0qw^V9SVIyCw`x(n4 zzFCUk#}lzCblY-@Xf@xhDKbF(n$zG${(LD~Ag?L(h};8ldw$qL`Nf)$ZwN2qP(o#72Nc+3lwCBj=3-)tV-?>l9n#i#q zT~N1tetRp@?hO#=V`>;V9QuF^G!6yO1e z6yO4f6yO856yOAm5DiRj$Rzs$0005nSp(vit?&dWe}d<#1tcp%1#X$GT51WFcXQk{ zmD?dSm~VZ%gs37!0znDh<4^2t0s(NU7(#kBO^h#BOc9fhAIyM*ECa?&u;TUeE>zp#Ic)9o z&&z>dXi3Bt5qDVa3bYL~D~qu9e*(VB0eylG&P-$Ma4_JT^YA-Xl^I36 z6F0?ghHH>bCpb8v@_B*T>}8m!JzM(5GI45?6%F`fd8h|e-?E!(;3Oc~j=kyv14(q9 z1lg&%T{p}Bn87_MzT?)#5{|8)-XI&MoivZ0$sP^=q{Wc;AeqMPFNF4T^@6HS`hb}Q zf59p>m;6+poRfeqm+#My#*`qnx!$+ksZ&EUf60cSY?Pu?;|fa{kwZpy8Kg|TlI7+vTLFi#s#{!3W)aWGZ2d%_=Ls3)l&caK*5U|Wcm1dbxIWTvIqE1mjPZLp4%^4m6}UyHq&^A;Y47$rCCuz$_dCH8qMs?A}lFv zNNTSdp*IWJco2>(Tls^|4oG=L`goWB|H}QO#fPBt1c#vW1&5&X28W>Y2Zx~Z2)Cf~ G30%(xsh0i# diff --git a/Doc/Eng/API2.md b/Doc/Eng/API2.md index 5319dbd..0aececf 100644 --- a/Doc/Eng/API2.md +++ b/Doc/Eng/API2.md @@ -23,7 +23,7 @@ http://194.1.237.94/api/v2/GenerateKeys As a result, JSON is returned, which contains the required result field with the value: * 0 - the request contains errors or the result is not possible to get (for example, there is no such account), -* 1 - successful execution of the query +* 1 or >1 - successful execution of the query text - the optional field contains a detailed description of the result @@ -52,20 +52,28 @@ return: 2)**/api/v2/CreateAccount** - create a new account (account). In Tere free account creation is possible only in the intervals of 10 seconds. The paid version is given in the example of 2 methods **Send** #### Parameters: * Name - account name up to 40 bytes -* PubKey - public key in hex-format +* PrivKey - private key in hex-format +* Wait - if the number 1 is set, the response to the request is not returned until the transaction is written to the blockchain (the response time to the request is increased to 18 seconds) example: ```js http://127.0.0.1/api/v2/CreateAccount { - "Name": "Hellow, world", - "PubKey": "0240EDF5ECB25D886FD58DB92A53914FAC975078C1C2EDD1AC292B70C7BC13461F" + "Name": "PrivTest02", + "PrivKey": "A2D45610FE8AC931F32480BFE3E78D26E45B0A4F88045D6518263DA12FA9C033", + "Wait":1 } ``` return: ```js -{"result":1,"text":"Added to timer","TxID":"DC316BD766AC654E0AF7260F2E010000","BlockNum":19795750} +{ + "result": 190552, + "text": "Add to blockchain", + "TxID": "04711036904F1F2DDF49CC7B2F010000", + "BlockNum": 19889100 +} ``` +result - returns the id (number) of the created account ## Send @@ -77,6 +85,7 @@ return: * ToID - the account number of the recipient, the number or public key in hex format (in this case, it will create a new account with the name specified in the first line of the description of the payment and the payment the account will be charged 10 Tera) * Amount - sum, floating-point number, or object format {SumCOIN,SumCENT} * Description - description of payment order (optional) +* Wait - if the number 1 is set, the response to the request is not returned until the transaction is written to the blockchain (the response time to the request is increased to 8 seconds) example1: @@ -87,28 +96,50 @@ http://127.0.0.1/api/v2/Send "FromPrivKey": "A2D45610FE8AC931F32480BFE3E78D26E45B0A4F88045D6518263DA12FA9C033", "ToID":190165, "Amount":10.5, - "Description":"Test" + "Description":"Тест", + "Wait":1 } ``` -example2 (create a new account): +return: +```js +{ + "result": 1, + "text": "Add to blockchain", + "TxID": "C08A0C18C1ABF4062B149B7C2F010000", + "BlockNum": 19889307 +} +``` + +example2 (создание нового счета): ```js http://127.0.0.1/api/v2/Send + { - "FromID": 190085, + "FromID": 190059, "FromPrivKey": "A2D45610FE8AC931F32480BFE3E78D26E45B0A4F88045D6518263DA12FA9C033", + "ToID22":190516, "ToID":"0240EDF5ECB25D886FD58DB92A53914FAC975078C1C2EDD1AC292B70C7BC13461F", "Amount":10, - "Description":"New account" + "Description":"New account", + "Wait":1 } ``` return: ```js -{"result":1,"text":"OK","TxID":"BE10810FDE7A1317D9DF51D62D010000","BlockNum":19781201} +{ + "result": 190551, + "text": "Add to blockchain", + "TxID": "9DD4869C4515B2A3340E887A2F010000", + "BlockNum": 19888776 +} ``` +result - returns the id (number) of the created account + + ## GetBalance 4)**/api/v2/GetBalance** - get account balance @@ -119,15 +150,16 @@ example: ```js http://127.0.0.1/api/v2/GetBalance { - "AccountID": 0 + "AccountID": 9 } ``` return: ```js { "result": 1, - "SumCOIN": 580222966, - "SumCENT": 527313901 + "SumCOIN": 5589146, + "SumCENT": 555765670, + "PubKey": "02769165A6F9950D023A415EE668B80BB96B5C9AE2035D97BDFB44F356175A44FF" } ``` @@ -137,7 +169,7 @@ return: #### Parameters: * TxID - Transaction ID in hex format -example: +example1: ```js http://127.0.0.1/api/v2/GetTransaction { @@ -166,6 +198,26 @@ return: "result": 1 } ``` +example2: +```js +http://127.0.0.1/api/v2/GetTransaction +{ + "TxID": "04711036904F1F2DDF49CC7B2F010000" +} +``` +return: +```js +{ + "Type": 100, + "Currency": 0, + "PubKey": "0240EDF5ECB25D886FD58DB92A53914FAC975078C1C2EDD1AC292B70C7BC13461F", + "Name": "PrivTest02", + "Adviser": 0, + "Smart": 0, + "Reserve": "000000", + "result": 190552 +} +``` ## GetHistoryTransactions diff --git a/Doc/Rus/API2.md b/Doc/Rus/API2.md index 23f1262..62f985c 100644 --- a/Doc/Rus/API2.md +++ b/Doc/Rus/API2.md @@ -1,6 +1,6 @@ # API v2 (для бирж и обменников) -API предназначено для облегчения написания сторонних приложений. На стороне сервера выполняется криптография и операции POW. Поэтому оно не рекомендуется для публичного доступа, т.к. не защищено от DDOS атак. Используйте его, если приложения такие как сервер биржи находятся в одной приватной сети. +API предназначено для облегчения написания сторонних приложений. На стороне сервера выполняется криптография и операции POW. Поэтому оно не рекомендуется для публичного доступа, т.к. нет защиты от DDOS атак. Используйте его, если приложения такие как сервер биржи находятся в одной приватной сети. Данный API доступен если на ноде запущен http-хостинг и включена константа USE_HARD_API_V2. @@ -22,7 +22,7 @@ http://194.1.237.94/api/v2/GenerateKeys В качестве результат возвращается JSON, который содержит обязательное поле result со значением: * 0 - запрос содержит ошибки или результат не возможно получить (например нет такого счета), -* 1 - успешное выполнение запроса +* 1 или >1 - успешное выполнение запроса (в случае запросов создания новых счетов и режимом Wait:1 здесь возвращается номер созданного счета) text - опциональное поле содержит подробное описание результата @@ -51,20 +51,28 @@ return: 2)**/api/v2/CreateAccount** - создание нового счета (аккаунта). В Тере бесплатное создание счета возможно только в промежутках из 10 секунд. Платный вариант приведен в примере 2 метода **Send** #### Параметры: * Name - имя счета до 40 байт -* PubKey - публичный ключ в hex-формате +* PrivKey - приватный ключ в hex-формате +* Wait - если установлена цифра 1, то ответ на запрос не возвращается до тех пор пока транзакция не будет записана в блокчейн (время ответа на запрос увеличивается до 18 сек) example: ```js http://127.0.0.1/api/v2/CreateAccount { - "Name": "Hellow, world", - "PubKey": "0240EDF5ECB25D886FD58DB92A53914FAC975078C1C2EDD1AC292B70C7BC13461F" + "Name": "PrivTest02", + "PrivKey": "A2D45610FE8AC931F32480BFE3E78D26E45B0A4F88045D6518263DA12FA9C033", + "Wait":1 } ``` return: ```js -{"result":1,"text":"Added to timer","TxID":"DC316BD766AC654E0AF7260F2E010000","BlockNum":19795750} +{ + "result": 190552, + "text": "Add to blockchain", + "TxID": "04711036904F1F2DDF49CC7B2F010000", + "BlockNum": 19889100 +} ``` +result - возвращает номер созданного аккаунта ## Send @@ -76,6 +84,7 @@ return: * ToID - номер счета получателя, число или публичный ключ в hex-формате (в этом случае будет создан новый счет с именем заданным в первой строке описания платежа и в качестве оплаты создания счета спишется 10 Тера) * Amount - сумма, число с плавающей точкой или объект в формате {SumCOIN,SumCENT} * Description - описание платежка (необязательный параметр) +* Wait - если установлена цифра 1, то ответ на запрос не возвращается до тех пор пока транзакция не будет записана в блокчейн (время ответа на запрос увеличивается до 8 сек) example1: @@ -86,27 +95,49 @@ http://127.0.0.1/api/v2/Send "FromPrivKey": "A2D45610FE8AC931F32480BFE3E78D26E45B0A4F88045D6518263DA12FA9C033", "ToID":190165, "Amount":10.5, - "Description":"Тест" + "Description":"Тест", + "Wait":1 } ``` +return: +```js +{ + "result": 1, + "text": "Add to blockchain", + "TxID": "C08A0C18C1ABF4062B149B7C2F010000", + "BlockNum": 19889307 +} +``` + example2 (создание нового счета): ```js http://127.0.0.1/api/v2/Send + { - "FromID": 190085, + "FromID": 190059, "FromPrivKey": "A2D45610FE8AC931F32480BFE3E78D26E45B0A4F88045D6518263DA12FA9C033", + "ToID22":190516, "ToID":"0240EDF5ECB25D886FD58DB92A53914FAC975078C1C2EDD1AC292B70C7BC13461F", "Amount":10, - "Description":"New account" + "Description":"New account", + "Wait":1 } ``` return: ```js -{"result":1,"text":"OK","TxID":"BE10810FDE7A1317D9DF51D62D010000","BlockNum":19781201} +{ + "result": 190551, + "text": "Add to blockchain", + "TxID": "9DD4869C4515B2A3340E887A2F010000", + "BlockNum": 19888776 +} ``` +result - возвращает номер созданного аккаунта + + ## GetBalance @@ -136,7 +167,7 @@ return: #### Параметры: * TxID - ИД транзакции в hex-формате -example: +example1: ```js http://127.0.0.1/api/v2/GetTransaction { @@ -166,6 +197,27 @@ return: } ``` +example2: +```js +http://127.0.0.1/api/v2/GetTransaction +{ + "TxID": "04711036904F1F2DDF49CC7B2F010000" +} +``` +return: +```js +{ + "Type": 100, + "Currency": 0, + "PubKey": "0240EDF5ECB25D886FD58DB92A53914FAC975078C1C2EDD1AC292B70C7BC13461F", + "Name": "PrivTest02", + "Adviser": 0, + "Smart": 0, + "Reserve": "000000", + "result": 190552 +} +``` + ## GetHistoryTransactions 6)**/api/v2/GetHistoryTransactions** - получить историю транзакций счета diff --git a/Source/core/base.js b/Source/core/base.js index dd63673..51e10e8 100644 --- a/Source/core/base.js +++ b/Source/core/base.js @@ -313,7 +313,7 @@ class STreeBuffer SaveValue(Hash, Value) { if(typeof Hash !== this.KeyType) - throw "MUST ONLY HASH ARRAY: " + Hash; + throw "MUST ONLY TYPE=" + this.KeyType + " in " + Hash; if(Value !== undefined) { var element = this.MetaTree1.find({hash:Hash}); diff --git a/Source/core/block-loader.js b/Source/core/block-loader.js index d4b2af6..c0e941f 100644 --- a/Source/core/block-loader.js +++ b/Source/core/block-loader.js @@ -753,7 +753,7 @@ module.exports = class CBlock extends require("./db/block-db") if(CompareArr(BlockDB.TreeHash, Block.TreeHash) == 0) { Block.TreeEq = true - Block.BodyFileNum = BlockDB.BodyFileNum + Block.Reserv500 = BlockDB.Reserv500 Block.TrDataPos = BlockDB.TrDataPos Block.TrDataLen = BlockDB.TrDataLen continue; @@ -856,7 +856,6 @@ module.exports = class CBlock extends require("./db/block-db") { if(IsZeroArr(Block.TreeHash)) { - Block.BodyFileNum = 0 Res = this.WriteBlockDB(Block) } else @@ -1124,7 +1123,6 @@ module.exports = class CBlock extends require("./db/block-db") } } } - Block.BodyFileNum = this.GetChainFileNum(Block.chain) Block.arrContent = arrContent var Ret = this.WriteBodyDB(Block); Block.TrCount = 0 diff --git a/Source/core/constant.js b/Source/core/constant.js index f876884..29fbc66 100644 --- a/Source/core/constant.js +++ b/Source/core/constant.js @@ -8,7 +8,7 @@ * Telegram: https://web.telegram.org/#/im?p=@terafoundation */ -global.UPDATE_CODE_VERSION_NUM = 891; +global.UPDATE_CODE_VERSION_NUM = 893; global.MIN_CODE_VERSION_NUM = 884; global.MINING_VERSION_NUM = 3; global.InitParamsArg = InitParamsArg; diff --git a/Source/core/db/block-db.js b/Source/core/db/block-db.js index a426f0b..93a2a39 100644 --- a/Source/core/db/block-db.js +++ b/Source/core/db/block-db.js @@ -164,10 +164,6 @@ module.exports = class CDB extends require("../code") } return num > 0 ? num - 1 : 0; } - GetChainFileNum(chain) - { - return 0; - } WriteBlockDB(Block) { var startTime = process.hrtime(); @@ -212,6 +208,34 @@ module.exports = class CDB extends require("../code") } return Ret; } + WriteBodyResultDB(Block) + { + var arrTr = Block.arrContentResult; + if(Block.TrDataPos && Block.TrDataLen && Block.VersionBody && arrTr && arrTr.length) + { + var FileItem = BlockDB.OpenDBFile(FILE_NAME_BODY, 1); + var FD = FileItem.fd; + var Size = arrTr.length * 6; + var Position = Block.TrDataPos + Block.TrDataLen - Size; + if(FileItem.size < Position + Size) + { + TO_ERROR_LOG("DB", 241, "Error Position in WriteBodyResultDB on block: " + Block.BlockNum) + return false; + } + var BufWrite = BufLib.GetNewBuffer(Size); + for(var i = 0; i < arrTr.length; i++) + { + BufWrite.Write(arrTr[i], "uint") + } + var written = fs.writeSync(FD, BufWrite, 0, BufWrite.length, Position); + if(written !== BufWrite.length) + { + TO_ERROR_LOG("DB", 242, "Error write to file block-chain : " + written + " <> " + BufWrite.length) + return false; + } + } + return true; + } WriteBodyDB(Block) { var FileItem = BlockDB.OpenDBFile(FILE_NAME_BODY, 1); @@ -233,9 +257,11 @@ module.exports = class CDB extends require("../code") arrSize[i] = 2 + body.length TrDataLen += arrSize[i] } + Block.VersionBody = 1 + TrDataLen += arrTr.length * 6 var BufWrite = BufLib.GetNewBuffer(TrDataLen); BufWrite.Write(arrTr.length, "uint16") - BufWrite.Write(0, "uint16") + BufWrite.Write(Block.VersionBody, "uint16") for(var i = 0; i < arrTr.length; i++) { var body = arrTr[i]; @@ -337,8 +363,9 @@ module.exports = class CDB extends require("../code") return false; } Block.arrContent = [] + Block.arrContentResult = [] var TrCount = BufRead.Read("uint16"); - var TrCountDapp = BufRead.Read("uint16"); + Block.VersionBody = BufRead.Read("uint16") if(TrCount <= MAX_TRANSACTION_COUNT) { for(var i = 0; i < TrCount; i++) @@ -348,6 +375,15 @@ module.exports = class CDB extends require("../code") break; Block.arrContent[i] = body } + if(Block.VersionBody === 1) + { + var Size = TrCount * 6; + BufRead.len = Block.TrDataLen - Size + for(var i = 0; i < TrCount; i++) + { + Block.arrContentResult[i] = BufRead.Read("uint") + } + } } Block.TrCount = Block.arrContent.length return true; @@ -475,14 +511,14 @@ module.exports = class CDB extends require("../code") } BlockHeaderToBuf(BufWrite, Block) { - Block.BodyFileNum = 0 + Block.Reserv500 = 0 var len = BufWrite.len; BufWrite.Write(Block.TreeHash, "hash") BufWrite.Write(Block.AddrHash, "hash") BufWrite.Write(Block.PrevHash, "hash") BufWrite.Write(Block.SumHash, "hash") BufWrite.Write(Block.SumPow, "uint") - BufWrite.Write(Block.BodyFileNum, "uint") + BufWrite.Write(Block.Reserv500, "uint") BufWrite.Write(Block.TrDataPos, "uint") BufWrite.Write(Block.TrDataLen, "uint32") BufWrite.len = len + BLOCK_HEADER_SIZE @@ -498,7 +534,7 @@ module.exports = class CDB extends require("../code") Block.PrevHash = BufRead.Read("hash") Block.SumHash = BufRead.Read("hash") Block.SumPow = BufRead.Read("uint") - Block.BodyFileNum = BufRead.Read("uint") + Block.Reserv500 = BufRead.Read("uint") Block.TrDataPos = BufRead.Read("uint") Block.TrDataLen = BufRead.Read("uint32") Block.TrCount = 0 @@ -593,9 +629,15 @@ module.exports = class CDB extends require("../code") if(App) { Tr.Script = App.GetScriptTransaction(Tr.body) - Tr.Verify = App.GetVerifyTransaction(BlockNum, Tr.Num, Tr.body) - if(Tr.Verify == 1) + Tr.Verify = App.GetVerifyTransaction(Block, BlockNum, Tr.Num, Tr.body) + if(Tr.Verify >= 1) + { Tr.VerifyHTML = "" + if(Tr.Verify > 1) + { + Tr.VerifyHTML += "(" + Tr.Verify + ")" + } + } else if(Tr.Verify == - 1) Tr.VerifyHTML = "" diff --git a/Source/core/html-server.js b/Source/core/html-server.js index 958b86a..cfb36d2 100644 --- a/Source/core/html-server.js +++ b/Source/core/html-server.js @@ -367,7 +367,7 @@ HTTPCaller.ToLogServer = function (Str) }; HTTPCaller.FindMyAccounts = function (Params) { - WALLET.FindMyAccounts(); + WALLET.FindMyAccounts(1); return {result:1}; }; HTTPCaller.GetAccount = function (id) diff --git a/Source/core/transaction-validator.js b/Source/core/transaction-validator.js index 5e4a5c0..e1f850e 100644 --- a/Source/core/transaction-validator.js +++ b/Source/core/transaction-validator.js @@ -92,6 +92,7 @@ module.exports = class CSmartContract extends require("./block-exchange") { DApps[key].OnWriteBlockStart(Block) } + var arrContentResult = []; var BlockNum = Block.BlockNum; var arr = Block.arrContent; if(arr) @@ -106,26 +107,46 @@ module.exports = class CSmartContract extends require("./block-exchange") var App = DAppByType[type]; if(App) { + App.ResultTx = 0 DApps.Accounts.BeginTransaction() var StrHex = GetHexFromArr(sha3(arr[i])); var item = global.TreeFindTX.LoadValue(StrHex); - global.CurTrItem = item + if(item) + global.CurTrItem = item.TX + else + global.CurTrItem = undefined var Result = App.OnWriteTransaction(Block, arr[i], BlockNum, i); + var SetResult = Result; + if(Result === true) + { + if(App.ResultTx) + SetResult = App.ResultTx + if(!DApps.Accounts.CommitTransaction(BlockNum, i)) + SetResult = 0 + } + else + { + DApps.Accounts.RollBackTransaction() + SetResult = 0 + } + if(SetResult === true) + SetResult = 1 + arrContentResult[i] = SetResult if(item) { var ResultStr = Result; - if(Result === true) + if(Result === true || typeof Result === "number") { ResultStr = "Add to blockchain" if(type === global.TYPE_TRANSACTION_FILE) ResultStr += ": file/" + BlockNum + "/" + i } - ToLogClient(ResultStr, item, true) + item.cmd = "RetFindTX" + item.ResultStr = "" + ResultStr + item.bFinal = 1 + item.Result = SetResult + process.send(item) } - if(Result === true) - DApps.Accounts.CommitTransaction(BlockNum, i) - else - DApps.Accounts.RollBackTransaction() global.CurTrItem = undefined } } @@ -136,6 +157,8 @@ module.exports = class CSmartContract extends require("./block-exchange") this.DeleteBlockFromHashTree(Block2) this.AddBlockToHashTree(Block) } + if(arrContentResult.length) + process.send({cmd:"WriteBodyResult", BlockNum:Block.BlockNum, arrContentResult:arrContentResult}) for(var key in DApps) { DApps[key].OnWriteBlockFinish(Block) diff --git a/Source/core/wallet.js b/Source/core/wallet.js index 5bd8940..f117550 100644 --- a/Source/core/wallet.js +++ b/Source/core/wallet.js @@ -108,7 +108,7 @@ class CApp { this.AccountMap = {} } - this.FindMyAccounts() + this.FindMyAccounts(0) if(bGo) this.SaveWallet() } @@ -230,11 +230,12 @@ class CApp { this.AccountMap[Data.Num] = 0 } - FindMyAccounts() + FindMyAccounts(bClean) { if(IsZeroArr(this.PubKeyArr)) return ; - this.AccountMap = {} + if(bClean) + this.AccountMap = {} DApps.Accounts.FindAccounts([this.PubKeyArr], this.AccountMap, 0) } GetAccountKey(Num) diff --git a/Source/dapp/accounts.js b/Source/dapp/accounts.js index 2707a61..bcea28e 100644 --- a/Source/dapp/accounts.js +++ b/Source/dapp/accounts.js @@ -363,8 +363,16 @@ class AccountApp extends require("./dapp") } } } - GetVerifyTransaction(BlockNum, TrNum, Body) + GetVerifyTransaction(Block, BlockNum, TrNum, Body) { + if(Block.VersionBody === 1) + { + var Result = Block.arrContentResult[TrNum]; + if(!Result) + return - 1; + else + return Result; + } var Type = Body[0]; var Find = 0; switch(Type) @@ -571,6 +579,7 @@ class AccountApp extends require("./dapp") { WALLET.OnCreateAccount(Account) } + this.ResultTx = Account.Num return true; } TRTransferMoney(Block, Body, BlockNum, TrNum, format_money_transfer, workstructtransfer) @@ -679,6 +688,7 @@ class AccountApp extends require("./dapp") Account.PubKey = Item.PubKey Account.Name = name this.WriteStateTR(Account, TrNum) + this.ResultTx = Account.Num Item.ID = Account.Num this.SendMoneyTR(Block, Data.Num, Account.Num, {SumCOIN:Item.SumCOIN, SumCENT:Item.SumCENT}, BlockNum, TrNum, TR.Description, TR.Description, 1) @@ -1164,7 +1174,7 @@ class AccountApp extends require("./dapp") { var DBChanges = this.DBChanges; if(DBChanges.RollBackTransaction) - return ; + return false; DBChanges.BlockMaxAccount = DBChanges.TRMaxAccount for(var key in DBChanges.TRMap) { @@ -1184,6 +1194,7 @@ class AccountApp extends require("./dapp") DBChanges.BlockEvent.push(DBChanges.TREvent[i]) } global.TickCounter = 0 + return true; } OnWriteNewAccountTR(Data, BlockNum, TrNum) { diff --git a/Source/dapp/dapp.js b/Source/dapp/dapp.js index 5eb5373..0853e0a 100644 --- a/Source/dapp/dapp.js +++ b/Source/dapp/dapp.js @@ -31,7 +31,7 @@ class DApp { return ""; } - GetVerifyTransaction(BlockNum, TrNum, Body) + GetVerifyTransaction(Block, BlockNum, TrNum, Body) { return 1; } diff --git a/Source/dapp/file.js b/Source/dapp/file.js index 01993c5..893e82d 100644 --- a/Source/dapp/file.js +++ b/Source/dapp/file.js @@ -33,7 +33,7 @@ class FileApp extends require("./dapp") ConvertBufferToStr(TR) return JSON.stringify(TR, "", 2); } - GetVerifyTransaction(BlockNum, TrNum, Body) + GetVerifyTransaction(Block, BlockNum, TrNum, Body) { return 1; } diff --git a/Source/dapp/smart.js b/Source/dapp/smart.js index d6c1bd8..bd72525 100644 --- a/Source/dapp/smart.js +++ b/Source/dapp/smart.js @@ -147,7 +147,7 @@ class SmartApp extends require("./dapp") } catch(e) { - Result = e + Result = "" + e } return Result; } @@ -169,7 +169,7 @@ class SmartApp extends require("./dapp") ConvertBufferToStr(TR) return JSON.stringify(TR, "", 2); } - GetVerifyTransaction(BlockNum, TrNum, Body) + GetVerifyTransaction(Block, BlockNum, TrNum, Body) { return 1; } diff --git a/Source/process/api-exchange.js b/Source/process/api-exchange.js index 2834990..40ee488 100644 --- a/Source/process/api-exchange.js +++ b/Source/process/api-exchange.js @@ -19,15 +19,17 @@ WebApi2.GenerateKeys = function (Params) }; WebApi2.CreateAccount = function (Params,response) { - if(typeof Params === "object" && Params.Name && Params.PubKey) + if(typeof Params === "object" && Params.Name && Params.PrivKey) { - var TR = {Type:TYPE_TRANSACTION_CREATE, Currency:Params.Currency, PubKey:GetArrFromHex(Params.PubKey), Name:Params.Name, Smart:Params.Smart, - }; + var KeyPair = crypto.createECDH('secp256k1'); + KeyPair.setPrivateKey(Buffer.from(GetArrFromHex(Params.PrivKey))); + var PubKey = KeyPair.getPublicKey('', 'compressed'); + var TR = {Type:TYPE_TRANSACTION_CREATE, Currency:Params.Currency, PubKey:PubKey, Name:Params.Name, Smart:Params.Smart, }; var Body = BufLib.GetBufferFromObject(TR, FORMAT_CREATE, 1000, {}, 1); Body = Body.slice(0, Body.len + 12); - SendTransaction(Body, TR, undefined, function (result,TR,Body) + SendTransaction(Body, TR, Params.Wait, function (result,text) { - var Result = {result:result < 1 ? 0 : 1, text:TR._text, TxID:GetHexFromArr(TR._TxID.slice(0, TR_TICKET_HASH_LENGTH + 6)), BlockNum:TR._BlockNum, + var Result = {result:result, text:text, TxID:GetHexFromArr(TR._TxID.slice(0, TR_TICKET_HASH_LENGTH + 6)), BlockNum:TR._BlockNum, Meta:Params.Meta, }; var Str = JSON.stringify(Result); response.end(Str); @@ -86,9 +88,9 @@ WebApi2.Send = function (Params,response) TR.Sign = DApps.Accounts.GetSignTransferTx(TR, GetArrFromHex(Params.FromPrivKey)); var Body = BufLib.GetBufferFromObject(TR, FORMAT_MONEY_TRANSFER3, MAX_TRANSACTION_SIZE, {}, 1); Body = Body.slice(0, Body.len + 12); - SendTransaction(Body, TR, undefined, function (result,TR,Body) + SendTransaction(Body, TR, Params.Wait, function (result,text) { - var Result = {result:result < 1 ? 0 : 1, text:TR._text, TxID:GetHexFromArr(TR._TxID.slice(0, TR_TICKET_HASH_LENGTH + 6)), BlockNum:TR._BlockNum, + var Result = {result:result, text:text, TxID:GetHexFromArr(TR._TxID.slice(0, TR_TICKET_HASH_LENGTH + 6)), BlockNum:TR._BlockNum, Meta:Params.Meta, }; var Str = JSON.stringify(Result); response.end(Str); @@ -103,7 +105,8 @@ WebApi2.GetBalance = function (Params,response) if(arr.length) { var Value = arr[0].Value; - var Result = {result:1, SumCOIN:Value.SumCOIN, SumCENT:Value.SumCENT, Meta:Params.Meta, }; + var Result = {result:1, SumCOIN:Value.SumCOIN, SumCENT:Value.SumCENT, PubKey:GetHexFromArr(arr[0].PubKey), Meta:Params.Meta, + }; return Result; } } @@ -133,6 +136,10 @@ WebApi2.GetTransaction = function (Params) ConvertBufferToStr(TR); TR.result = 1; TR.Meta = Params.Meta; + if(Block.VersionBody === 1 && Block.arrContentResult) + { + TR.result = Block.arrContentResult[i]; + } return TR; } } @@ -198,7 +205,7 @@ function CreateHashBodyPOWInnerMinPower(TR,arr,MinPow,startnonce) } }; -function SendTransaction(Body,TR,SumPow,F) +function SendTransaction(Body,TR,Wait,F) { if(Body.length > 16000) { @@ -207,6 +214,8 @@ function SendTransaction(Body,TR,SumPow,F) F(1, TR, Body); return ; } + global.GlobalRunID++; + let WebID = global.GlobalRunID; CreateNonceAndSend(0, 0); function CreateNonceAndSend(startnonce,NumNext) @@ -218,8 +227,8 @@ function CreateNonceAndSend(startnonce,NumNext) F(0, TR, Body); return ; } - var nonce = CreateHashBodyPOWInnerMinPower(TR, Body, SumPow, startnonce); - process.RunRPC("AddTransactionFromWeb", GetHexFromArr(Body), function (Err,text) + var nonce = CreateHashBodyPOWInnerMinPower(TR, Body, undefined, startnonce); + process.RunRPC("AddTransactionFromWeb", {WebID:WebID, HexValue:GetHexFromArr(Body)}, function (Err,text) { TR._result = Err ? 0 : 1; TR._text = text; @@ -239,7 +248,14 @@ function CreateNonceAndSend(startnonce,NumNext) return ; } } - F(TR._result, TR, Body); + if(Wait && TR._result) + { + global.GlobalRunMap[WebID] = F; + } + else + { + F(TR._result < 1 ? 0 : 1, text); + } }); }; }; diff --git a/Source/process/main-process.js b/Source/process/main-process.js index ad80c84..e9ba711 100644 --- a/Source/process/main-process.js +++ b/Source/process/main-process.js @@ -126,13 +126,13 @@ function OnMessageWeb(msg) } }; -function AddTransactionFromWeb(HexValue) +function AddTransactionFromWeb(Params) { - var body = GetArrFromHex(HexValue); + var body = GetArrFromHex(Params.HexValue); if(global.TX_PROCESS && global.TX_PROCESS.Worker) { var StrHex = GetHexFromArr(sha3(body)); - global.TX_PROCESS.Worker.send({cmd:"FindTX", TX:StrHex}); + global.TX_PROCESS.Worker.send({cmd:"FindTX", TX:StrHex, Web:1, WebID:Params.WebID}); } var Res = SERVER.AddTransaction({body:body}, 1); var text = AddTrMap[Res]; @@ -270,10 +270,27 @@ function StartChildProcess(Item) } ToLogClient(msg.Str, msg.StrKey, msg.bFinal); break; + case "RetFindTX": + if(WebProcess && WebProcess.Worker) + { + WebProcess.Worker.send(msg); + if(msg.Web) + break; + } + ToLogClient(msg.ResultStr, msg.TX, msg.bFinal); + break; case "online": if(ITEM.Worker) ToLog("RUNING " + ITEM.Name + " : " + msg.message + " pid: " + ITEM.Worker.pid); break; + case "WriteBodyResult": + var Block = SERVER.ReadBlockDB(msg.BlockNum); + if(Block) + { + Block.arrContentResult = msg.arrContentResult; + SERVER.WriteBodyResultDB(Block); + } + break; default: if(ITEM.OnMessage) { diff --git a/Source/process/tx-process.js b/Source/process/tx-process.js index 834c20f..3b12f8b 100644 --- a/Source/process/tx-process.js +++ b/Source/process/tx-process.js @@ -57,7 +57,7 @@ process.on('message', function (msg) process.send({cmd:"retcall", id:msg.id, Err:Err, Params:Ret}); break; case "FindTX": - global.TreeFindTX.SaveValue(msg.TX, msg.TX); + global.TreeFindTX.SaveValue(msg.TX, msg); break; case "SetSmartEvent": global.TreeFindTX.SaveValue("Smart:" + msg.Smart, 1); diff --git a/Source/process/web-process.js b/Source/process/web-process.js index 11ef1dd..6f20e76 100644 --- a/Source/process/web-process.js +++ b/Source/process/web-process.js @@ -86,6 +86,21 @@ process.on('message', function (msg) ToLogClient0(msg.Str, msg.StrKey, msg.bFinal); break; } + case "RetFindTX": + { + if(msg.WebID) + { + var F = global.GlobalRunMap[msg.WebID]; + if(F) + { + delete global.GlobalRunMap[msg.WebID]; + F(msg.Result, msg.ResultStr); + break; + } + } + ArrLogClient.push({text:msg.ResultStr, key:msg.TX, final:msg.bFinal, }); + break; + } } }); @@ -600,7 +615,7 @@ HostingCaller.SendTransactionHex = function (Params,response) { if(typeof Params !== "object" || !Params.Hex) return {result:0, text:"object requre"}; - process.RunRPC("AddTransactionFromWeb", Params.Hex, function (Err,text) + process.RunRPC("AddTransactionFromWeb", {HexValue:Params.Hex}, function (Err,text) { var Result = {result:!Err, text:text}; var Str = JSON.stringify(Result); @@ -714,8 +729,8 @@ HostingCaller.DappStaticCall = function (Params) return {result:0}; return HTTPCaller.DappStaticCall(Params); }; -var GlobalRunID = 0; -var GlobalRunMap = {}; +global.GlobalRunID = 0; +global.GlobalRunMap = {}; process.RunRPC = function (Name,Params,F) { if(F)