| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- <?php
- namespace App\Module\App;
- use App\Module\Ulogic\Enum\WALLET_ADDRESS_TYPE;
- use App\Module\Ulogic\Model\WalletAddress;
- use App\Module\Ulogic\Services\UserRelationService;
- use App\Module\User\Model\User;
- use Illuminate\Support\Facades\Cache;
- use Illuminate\Support\Facades\DB;
- use UCore\Exception\ValidateException;
- /**
- * 助记词
- */
- class Mnemon
- {
- const KEY = 'INIT_WORD_';
- const TTL = 86400;
- /**
- * @param int $wordCount
- * @return object|\FurqanSiddiqui\BIP39\Mnemonic
- * @throws \FurqanSiddiqui\BIP39\Exception\Bip39EntropyException
- * @throws \FurqanSiddiqui\BIP39\Exception\Bip39MnemonicException
- * @throws \Random\RandomException
- * 生成助记词
- */
- public static function generate(int $userId): object
- {
- // 生成助记词
- $mnemonic = \FurqanSiddiqui\BIP39\BIP39::fromRandom(
- \FurqanSiddiqui\BIP39\Language\English::getInstance(),
- wordCount: 12
- );
- // 存入缓存
- $key = self::KEY . $userId;
- Cache::set($key, $mnemonic->entropy, self::TTL);
- return $mnemonic;
- }
- /**
- * @param $word
- * @param $userId
- * @param bool $isRegister
- * @return \FurqanSiddiqui\BIP39\Mnemonic|string
- * @throws \FurqanSiddiqui\BIP39\Exception\Bip39MnemonicException
- * 验证助记词
- */
- public static function wordsToMnemonic($word = '', $userId = 0, $isRegister = true)
- {
- $word = explode(',', $word);
- $mnemonic = \FurqanSiddiqui\BIP39\BIP39::fromWords(
- $word,
- \FurqanSiddiqui\BIP39\Language\English::getInstance()
- );
- $userWordEntropy = $mnemonic->entropy;
- if ($isRegister) {
- $redisKey = self::KEY . $userId;
- if (!Cache::has($redisKey)) {
- throw new ValidateException(null,'助记词失效');
- }
- $cacheWordEntropy = Cache::get(self::KEY . $userId);
- }else{
- $cacheWordEntropy = User::getUserInfoByCondition('user_id',$userId)->password;
- }
- if ($userWordEntropy !== $cacheWordEntropy) {
- throw new ValidateException(null,'助记词验证失败');
- }
- // 不需要注册,返回true
- if (!$isRegister) {
- return true;
- }
- // 事务
- DB::beginTransaction();
- try {
- // 生成uraus地址
- $addStr = WalletAddress::createAddress();
- $walletAddress = '0xuraus' . $addStr;
- WalletAddress::createRow($userId, $walletAddress);
- // 写入user表数据
- User::updateByUserId($userId, 'password', $cacheWordEntropy);
- // 绑定用户关系
- UserRelationService::createRelation($userId);
- Db::commit();
- return true;
- } catch (\Exception $e) {
- DB::rollBack();
- return false;
- }
- }
- }
|