This commit is contained in:
progr76@gmail.com 2019-02-16 20:08:41 +03:00
parent 4087d50a65
commit 5affe69fe0
19 changed files with 304 additions and 77 deletions

Binary file not shown.

Binary file not shown.

View File

@ -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

View File

@ -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** - получить историю транзакций счета

View File

@ -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});

View File

@ -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

View File

@ -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;

View File

@ -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 = "<B style='color:green'>✔</B>"
if(Tr.Verify > 1)
{
Tr.VerifyHTML += "(" + Tr.Verify + ")"
}
}
else
if(Tr.Verify == - 1)
Tr.VerifyHTML = "<B style='color:red'>✘</B>"

View File

@ -367,7 +367,7 @@ HTTPCaller.ToLogServer = function (Str)
};
HTTPCaller.FindMyAccounts = function (Params)
{
WALLET.FindMyAccounts();
WALLET.FindMyAccounts(1);
return {result:1};
};
HTTPCaller.GetAccount = function (id)

View File

@ -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)

View File

@ -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)

View File

@ -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)
{

View File

@ -31,7 +31,7 @@ class DApp
{
return "";
}
GetVerifyTransaction(BlockNum, TrNum, Body)
GetVerifyTransaction(Block, BlockNum, TrNum, Body)
{
return 1;
}

View File

@ -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;
}

View File

@ -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;
}

View File

@ -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);
}
});
};
};

View File

@ -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)
{

View File

@ -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);

View File

@ -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)