EosBase.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. <?php
  2. /**
  3. * EOS相关操作
  4. * User: ben
  5. * Date: 2018/9/19
  6. * Time: 下午2:59
  7. */
  8. class EosBase extends Singleton {
  9. /**
  10. * 解锁钱包
  11. * @param string $name 钱包名 [0-9a-f]{12}
  12. * @param string $password 钱包名对应的密码
  13. */
  14. function unlockWallet($name = null, $password = null) {
  15. $name = $name ?: $GLOBALS['walletName'];
  16. $password = $password ?: $GLOBALS['walletPwd'];
  17. // 解锁钱包
  18. $cmd = "cleos wallet unlock -n {$name} --password {$password}";
  19. exec($cmd);
  20. }
  21. /**
  22. * 获取链的概要信息
  23. * @return mixed
  24. */
  25. static function getInfo() {
  26. $cmd = "cleos -u {$GLOBALS['eosUrl']} get info";
  27. $json = self::execCmd($cmd);
  28. return json_decode($json, true);
  29. }
  30. /**
  31. * eos或gt币转账给用户
  32. * @param $from
  33. * @param $to
  34. * @param $amount
  35. * @param $memo
  36. * @param $transaction_type
  37. * @param $player_transaction_id
  38. * @return array
  39. */
  40. public function transfer($from, $to, $amount, $memo, $transaction_type, $player_transaction_id = '') {
  41. $type = strpos(strtolower($amount), 'eos') === false ? 'gt' : 'eos';
  42. if ($type == 'gt') {
  43. // $from = $GLOBALS['codeGtAdmin'];
  44. $cmd = "cleos -u {$GLOBALS['eosUrl']} push action eosgetgtoken transfer '[ \"{$from}\", \"{$to}\", \"{$amount}\", \"{$memo}\" ]' -p {$from} -j";
  45. } elseif ($type == 'eos') {
  46. // $from = $GLOBALS['codeAdmin'];
  47. $cmd = "cleos -u {$GLOBALS['eosUrl']} transfer {$from} {$to} '{$amount}' '{$memo}' -j";
  48. } else {
  49. return null;
  50. }
  51. $json = self::execCmd($cmd);
  52. $log = [
  53. 'player_transaction_id' => $player_transaction_id,
  54. 'transaction_type' => $transaction_type,
  55. 'from' => $from,
  56. 'to' => $to,
  57. 'cmd' => $cmd,
  58. 'json' => $json,
  59. ];
  60. // 记录交易,失败重试
  61. return self::logTrans($log);
  62. }
  63. /**
  64. * 当前交易的块id
  65. * @var int
  66. */
  67. static $last_json = '';
  68. static $last_trx_id = 0;
  69. /**
  70. * 记录交易,并定时检查是否失效了
  71. * @param $data [`transaction_id`, `player_transaction_id`, `transaction_type`, `from`, `to`, `cmd`, `transaction_state`, `json`, `retry_times`]
  72. * @return array
  73. */
  74. static function logTrans($data) {
  75. self::$last_json = $data['json'];
  76. $objTrans = new TableHelper('transaction_log', 'dw_eos');
  77. $ret = [];
  78. $flag = false;
  79. if (!$data['transaction_id']) {
  80. if (!$data['json']) {
  81. self::_fillId($data);
  82. $data['transaction_state'] = -1;
  83. } else {
  84. $ret = json_decode($data['json'], true);
  85. $data['transaction_id'] = $ret['transaction_id'];
  86. if ($data['transaction_id']) {
  87. $flag = true;
  88. $data['block_num'] = $ret['processed']['block_num'];
  89. } else {
  90. // 没有id,就需要填充
  91. self::_fillId($data);
  92. $data['transaction_state'] = -1;
  93. }
  94. }
  95. }
  96. self::$last_trx_id = $data['transaction_id'];
  97. $data['console'] = $data['console'] ?: $ret['processed']['action_traces'][0]['console'];
  98. $data['create_time'] = date('Y-m-d H:i:s');
  99. $objTrans->addObject($data);
  100. if ($flag) {
  101. // return $data['transaction_id'];
  102. return $data;
  103. } else {
  104. return null;
  105. }
  106. }
  107. private static function _fillId(&$data) {
  108. $objTrans = new TableHelper('transaction_log', 'dw_eos');
  109. $count = $objTrans->getCount();
  110. $rand = rand(1000, 9999);
  111. $data['transaction_id'] = "unknown:{$count}:{$rand}";
  112. }
  113. /**
  114. * 获取真正的块id
  115. * @param $trxId
  116. * @param int $block_num
  117. *
  118. * @return mixed
  119. */
  120. static function getRealBlockNum($trxId, $block_num = 0) {
  121. if ($block_num || ENV == ENV_DEV) {
  122. $ret = self::getTransaction2($trxId, $block_num);
  123. } else {
  124. $ret = self::getTrxBySpark($trxId);
  125. }
  126. return $ret['block_num'];
  127. }
  128. static function getTrxBySpark($transaction_id) {
  129. $api_key = '37400d93f3c7eb64428585f1cd355fe8';
  130. $url = "https://api.eospark.com/api?module=transaction&action=get_transaction_detail_info&apikey={$api_key}&trx_id={$transaction_id}";
  131. $objHttp = new dwHttp();
  132. $data = null;
  133. for ($i = 1; $i <= 3; $i++) {
  134. $json = $objHttp->get2($url);
  135. $data = json_decode($json, true);
  136. if ($data['errno'] == 0) {
  137. return $data['data'];
  138. } else {
  139. sleep($i / 2);
  140. }
  141. }
  142. return $data;
  143. }
  144. /**
  145. * 获取交易详情
  146. * @param string $transaction_id
  147. * @param int $block_num_hint
  148. * @return string
  149. */
  150. static function getTransaction($transaction_id, $block_num_hint) {
  151. $api = $GLOBALS['eosUrl'] . 'v1/history/get_transaction';
  152. $data = ["id" => $transaction_id];
  153. $block_num_hint = (int)$block_num_hint;
  154. if ($block_num_hint) {
  155. $data['block_num_hint'] = $block_num_hint;
  156. }
  157. $json = null;
  158. for ($i = 0; $i < 4; $i++) {
  159. $post_json = json_encode($data);
  160. $json = (new dwHttp)->post2($api, $post_json, 3, 3);
  161. $trx = json_decode($json, true);
  162. if ($trx['id']) {
  163. return $json;
  164. } else {
  165. $data['block_num_hint']++;
  166. }
  167. }
  168. return $json;
  169. }
  170. /**
  171. * 获取账号信息
  172. * @param $userName
  173. *
  174. * @return string
  175. */
  176. static function getAccount($userName) {
  177. $cmd = "cleos -u {$GLOBALS['eosUrl']} get account {$userName} -j";
  178. return self::execCmd($cmd, false);
  179. }
  180. /**
  181. * 获取余额
  182. * @param $userName
  183. * @param $code
  184. *
  185. * @return float
  186. */
  187. public static function getBalance($userName, $code = 'eosio.token') {
  188. $cmd = "cleos -u {$GLOBALS['eosUrl']} get currency balance {$code} {$userName}";
  189. $result = self::execCmd($cmd);
  190. $balance = (float) $result;
  191. return $balance * 10000;
  192. }
  193. /**
  194. * 获取块信息
  195. * @param $block_num
  196. *
  197. * @return array
  198. */
  199. public static function getBlock($block_num) {
  200. $cmd = "cleos -u {$GLOBALS['eosUrl']} get block {$block_num}";
  201. $json = self::execCmd($cmd);
  202. $json = str_replace("\n", '', $json);
  203. $info = json_decode($json, true);
  204. return $info;
  205. }
  206. /**
  207. * 获取块id
  208. * @param $block_num
  209. *
  210. * @return array
  211. */
  212. public static function getBlockId($block_num) {
  213. $cmd = "cleos -u {$GLOBALS['eosUrl']} get block {$block_num}";
  214. $json = self::execCmd($cmd);
  215. $json = str_replace("\n", '', $json);
  216. $info = json_decode($json, true);
  217. if ($info && $info['id']) {
  218. $block_id = $info['id'];
  219. } else {
  220. $hex = dechex($block_num);
  221. $hex = sprintf("%08s", $hex);
  222. preg_match("/\"({$hex}[0-9a-fA-F]{56})\"/", $json, $matches);
  223. $block_id = $matches[1];
  224. }
  225. return $block_id;
  226. }
  227. static function execCmd($cmd, $writeLog = true) {
  228. self::$last_json = null;
  229. $startTime = microtime(true);
  230. if (strpos($cmd, ' 2>&1') === false) {
  231. $cmd = $cmd .' 2>&1';
  232. }
  233. // 同时输出错误信息
  234. $json = shell_exec($cmd);
  235. $msg = "{$cmd}, ret:" . substr($json, 0, 100);
  236. if ($writeLog) {
  237. CallLog::logModuleCall("Shell:", $msg, null, $json, $startTime);
  238. CallLog::flushLogs();
  239. }
  240. self::$last_json = $json;
  241. return $json;
  242. }
  243. static function log($msg) {
  244. $date = date('Y-m-d H:i:s', time());
  245. print_r("[{$date}], {$msg}\n");
  246. }
  247. /**
  248. * 重试多次获取交易id
  249. * @param $transaction_id
  250. * @param int $block_num_hint
  251. * @param int $maxTimes
  252. * @param int $times
  253. *
  254. * @return mixed
  255. */
  256. static function getTransaction2($transaction_id, $block_num_hint, $maxTimes = 3, $times = 0) {
  257. // 检验交易id是否是当前用户,当前gameid
  258. $json = self::getTransaction($transaction_id, $block_num_hint);
  259. $ret = json_decode($json, true);
  260. if ($ret['error']) {
  261. // 3040011 The transaction can not be found
  262. if ($ret['error']['code'] == 3040011) {
  263. if ($times < $maxTimes) {
  264. Tool::sleep($times);
  265. return self::getTransaction2($transaction_id, $block_num_hint, $maxTimes, $times + 1);
  266. } else {
  267. Response::error(CODE_PARAM_ERROR, "transaction id:{$transaction_id} is not found.");
  268. }
  269. }
  270. }
  271. return $ret;
  272. }
  273. static function getActions($account, $limit = 50, $p = 1, $ascendOrder = false){
  274. $p = (int)$p ?: 1;
  275. $pos = $ascendOrder ? $limit * ($p - 1) : -1;//升序支持分页,降序不支持分页,仅能从最尾部开始
  276. $offset = $limit - 1;
  277. $cmd = "cleos -u {$GLOBALS['eosUrl']} get actions -j {$account} {$pos} {$offset}";
  278. $actions = [];
  279. for ($i = 0; $i < 5; $i ++) {
  280. $json = self::execCmd($cmd);
  281. @$data = json_decode($json, 1) ?: [];
  282. if (isset($data['actions']) && is_array($data['actions'])) {
  283. $actions = $data['actions'];
  284. if (is_array($actions) && count($actions) == $limit) {
  285. break;//由于节点的不稳定性,所以要求一定要拿到actions,并争取非尾页的条数等于期望条数
  286. }
  287. }
  288. }
  289. return $actions;
  290. }
  291. }