以太坊ETH轉(zhuǎn)賬

本文介紹以太坊(Ethereum)的轉(zhuǎn)賬,依據(jù)web3j庫實(shí)現(xiàn)。

概念介紹

DSA一種公開密鑰算法,它不能用作加密,只用作數(shù)字簽名。參考
ECDSA橢圓曲線數(shù)字簽名算法(ECDSA)是使用橢圓曲線密碼(ECC)對數(shù)字簽名算法(DSA)的加密。生成的r、s簽名值參考

一、解碼錢包

也就是是根據(jù)用戶密碼從錢包讀出keystore信息。這基本就是錢包生成的逆向流程。
1.將用戶密碼根據(jù)scrypt算法重新生成derivedKey.如下圖紅框所示,跟create()相互對照
2.根據(jù)derivedKey調(diào)用performCipherOperation()解密方法得到私鑰。如下圖藍(lán)框所示,跟create()相互對照
3.將私鑰傳給ECKeyPair::create()便可重新得到公鑰。具體調(diào)用Sign::publicKeyFromPrivate():BigInteger感興趣的可以追進(jìn)去看看。
4.根據(jù)ECKeyPair生成Credentials類,這個(gè)類主要包含ECKeyPair和錢包地址。
這個(gè)地方需要注意的是,錢包地址是重新根據(jù)公鑰生成的,而不是從文件里讀取出來。
大伙想一下這樣做有什么好處?(安全唄,這不是p話么,放文件里被篡改了咋辦。)

decrypt.jpg

具體代碼

//Wallet.java內(nèi)解碼錢包
public static ECKeyPair decrypt(String password, WalletFile walletFile)throws CipherException {
    validate(walletFile);
    WalletFile.Crypto crypto = walletFile.getCrypto();
    byte[] mac = Numeric.hexStringToByteArray(crypto.getMac());
    byte[] iv = Numeric.hexStringToByteArray(crypto.getCipherparams().getIv());
    byte[] cipherText = Numeric.hexStringToByteArray(crypto.getCiphertext());
    byte[] derivedKey;
    //獲得scrypt加密的相關(guān)參數(shù),并解碼用戶密碼。
    WalletFile.KdfParams kdfParams = crypto.getKdfparams();
    if (kdfParams instanceof WalletFile.ScryptKdfParams) {
        WalletFile.ScryptKdfParams scryptKdfParams =
                (WalletFile.ScryptKdfParams) crypto.getKdfparams();
        int dklen = scryptKdfParams.getDklen();
        int n = scryptKdfParams.getN();
        int p = scryptKdfParams.getP();
        int r = scryptKdfParams.getR();
        byte[] salt = Numeric.hexStringToByteArray(scryptKdfParams.getSalt());
        derivedKey = generateDerivedScryptKey(
                password.getBytes(Charset.forName("UTF-8")), salt, n, r, p, dklen);
    } else if (kdfParams instanceof WalletFile.Aes128CtrKdfParams) {
        WalletFile.Aes128CtrKdfParams aes128CtrKdfParams =
                (WalletFile.Aes128CtrKdfParams) crypto.getKdfparams();
        int c = aes128CtrKdfParams.getC();
        String prf = aes128CtrKdfParams.getPrf();
        byte[] salt = Numeric.hexStringToByteArray(aes128CtrKdfParams.getSalt());
        derivedKey = generateAes128CtrDerivedKey(
                password.getBytes(Charset.forName("UTF-8")), salt, c, prf);
    } else {
        throw new CipherException("Unable to deserialize params: " + crypto.getKdf());
    }
    byte[] derivedMac = generateMac(derivedKey, cipherText);
    if (!Arrays.equals(derivedMac, mac)) {
        throw new CipherException("Invalid password provided");
    }
    byte[] encryptKey = Arrays.copyOfRange(derivedKey, 0, 16);
    //根據(jù)用戶密碼生成的encryptKey解碼cipherText獲得私鑰
    byte[] privateKey = performCipherOperation(Cipher.DECRYPT_MODE, iv, encryptKey, cipherText);
    return ECKeyPair.create(privateKey);
}

//Credentials.java內(nèi),根據(jù)ECKeyPair參數(shù)重新獲取地址并保存到當(dāng)前類內(nèi)。
public static Credentials create(ECKeyPair ecKeyPair) {
    String address = Numeric.prependHexPrefix(Keys.getAddress(ecKeyPair));
    return new Credentials(ecKeyPair, address);
}

經(jīng)過上面的步驟我們便解碼了錢包,后面就可以根據(jù)這些信息執(zhí)行轉(zhuǎn)賬功能了。

二、獲取Nonce

nonce:整數(shù)類型,會隨著賬戶下的交易不斷累加。作用是“防止交易的重播攻擊”。
我們通過調(diào)用ethscan的相關(guān)接口查詢到上次交易的nonce值,此值從0開始。

三、代碼處理

開始之前先介紹一個(gè)r、s、v的概念,其中r、s便是ECDSA簽名值。v是chainid.
1.根據(jù)nonce以及gasPrice、gasLimit等初始化RawTransaction類
也就是交易描述文件。
RawTransaction.createTransaction()
2.根據(jù)描述文件生成byte文件。TransactionEncoder.signMessage()
此文件為在網(wǎng)絡(luò)上傳輸?shù)奈募4瞬襟E會根據(jù)ECDSA進(jìn)行數(shù)字簽名以及加密。
3.調(diào)用api?action=eth_sendRawTransaction將描述文件發(fā)送到相關(guān)服務(wù)器。
4.服務(wù)器將此文件廣播到ETH公鏈。
接口調(diào)用代碼,具體見Github內(nèi)TransactionService.kt類

class TransactionService : IntentService("Transaction Service") {

    private var builder: NotificationCompat.Builder? = null
    internal val mNotificationId = 153

    override fun onHandleIntent(intent: Intent?) {
        sendNotification()
        try {
            val fromAddress = intent!!.getStringExtra("FROM_ADDRESS")
            val toAddress = intent.getStringExtra("TO_ADDRESS")
            val amount = intent.getStringExtra("AMOUNT")
            val gas_price = intent.getStringExtra("GAS_PRICE")
            val gas_limit = intent.getStringExtra("GAS_LIMIT")
            val data = intent.getStringExtra("DATA")
            val password = intent.getStringExtra("PASSWORD")

            val keys = WalletStorage.getInstance(applicationContext).getFullWallet(applicationContext, password, fromAddress)

            EtherscanAPI.INSTANCE.getNonceForAddress(fromAddress)
                    .subscribe(
                            object : SingleObserver<NonceForAddress> {
                                override fun onSuccess(t: NonceForAddress) {
                                    if (t.result.length < 2) return

                                    val nonce = BigInteger(t.result.substring(2), 16)

                                    val tx = RawTransaction.createTransaction(
                                            nonce,
                                            BigInteger(gas_price),
                                            BigInteger(gas_limit),
                                            toAddress,
                                            BigDecimal(amount).multiply(ExchangeCalculator.ONE_ETHER).toBigInteger(),
                                            data
                                    )

                                    Log.d("Aaron",
                                            "Nonce: " + tx.nonce + "\n" +
                                                    "gasPrice: " + tx.gasPrice + "\n" +
                                                    "gasLimit: " + tx.gasLimit + "\n" +
                                                    "To: " + tx.to + "\n" +
                                                    "Amount: " + tx.value + "\n" +
                                                    "Data: " + tx.data
                                    )

                                    val signed = TransactionEncoder.signMessage(tx, 1.toByte(), keys)

                                    forwardTX(signed)
                                }

                                override fun onSubscribe(d: Disposable) {
                                }

                                override fun onError(e: Throwable) {
                                    error("Can't connect to network, retry it later")
                                }

                            }
                    )

        } catch (e: Exception) {
            error("Invalid Wallet Password!")
            e.printStackTrace()
        }

    }

    @Throws(IOException::class)
    private fun forwardTX(signed: ByteArray) {

        EtherscanAPI.INSTANCE.forwardTransaction("0x" + Hex.toHexString(signed))
                .subscribe(
                        object : SingleObserver<ForwardTX> {
                            override fun onSuccess(t: ForwardTX) {
                                if (!TextUtils.isEmpty(t.result)) {
                                    suc(t.result)
                                } else {
                                    var errormsg = t.error.message
                                    if (errormsg.indexOf(".") > 0)
                                        errormsg = errormsg.substring(0, errormsg.indexOf("."))
                                    error(errormsg) // f.E Insufficient funds
                                }
                            }

                            override fun onSubscribe(d: Disposable) {
                            }

                            override fun onError(e: Throwable) {
                                error("Can't connect to network, retry it later")
                            }


                        }
                )
    }

    private fun suc(hash: String) {
        builder!!
                .setContentTitle(getString(R.string.notification_transfersuc))
                .setProgress(100, 100, false)
                .setOngoing(false)
                .setAutoCancel(true)
                .setContentText("")

        val main = Intent(this, MainActivity::class.java)
        main.putExtra("STARTAT", 2)
        main.putExtra("TXHASH", hash)

        val contentIntent = PendingIntent.getActivity(this, 0,
                main, PendingIntent.FLAG_UPDATE_CURRENT)
        builder!!.setContentIntent(contentIntent)

        val mNotifyMgr = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        mNotifyMgr.notify(mNotificationId, builder!!.build())
    }

    private fun error(err: String) {
        builder!!
                .setContentTitle(getString(R.string.notification_transferfail))
                .setProgress(100, 100, false)
                .setOngoing(false)
                .setAutoCancel(true)
                .setContentText(err)

        val main = Intent(this, MainActivity::class.java)
        main.putExtra("STARTAT", 2)

        val contentIntent = PendingIntent.getActivity(this, 0,
                main, PendingIntent.FLAG_UPDATE_CURRENT)
        builder!!.setContentIntent(contentIntent)

        val mNotifyMgr = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        mNotifyMgr.notify(mNotificationId, builder!!.build())
    }

    private fun sendNotification() {
        builder = NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_notification)
                .setColor(0x2d435c)
                .setTicker(getString(R.string.notification_transferingticker))
                .setContentTitle(getString(R.string.notification_transfering_title))
                .setContentText(getString(R.string.notification_might_take_a_minute))
                .setOngoing(true)
                .setProgress(0, 0, true)
        val mNotifyMgr = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        mNotifyMgr.notify(mNotificationId, builder!!.build())
    }


}

Git地址:https://github.com/snailflying/ETHWallet

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 所有貨幣都需要一些方法來控制供應(yīng),并強(qiáng)制執(zhí)行各種安全屬性以防止作弊。在法定貨幣方面,像中央銀行這樣的組織控制貨幣供...
    Nutbox_Lab閱讀 3,346評論 1 3
  • 一、快速術(shù)語檢索 比特幣地址:(例如:1DSrfJdB2AnWaFNgSbv3MZC2m74996JafV)由一串...
    不如假如閱讀 16,581評論 4 87
  • 本文是對以太坊文檔 Ethereum Frontier Guide 和 Ethereum Homestead 的整...
    趁風(fēng)卷閱讀 9,769評論 0 16
  • 常??吹铰牭侥承┤宋飫钪狙葜v,或在高校站臺,或在大會鼓吹,天花亂墜,說自己如何如何奮斗,如何如何經(jīng)歷坎坷,如何命懸...
    大陳子閱讀 1,060評論 0 1
  • 早上刷臉打卡的時(shí)候,看見機(jī)器屏幕上去年錄進(jìn)去的那張臉。默默地想,要是哪天識別不出來了就好了。至少說明,要么我可以不...
    蘇小白說閱讀 366評論 5 6

友情鏈接更多精彩內(nèi)容