summaryrefslogtreecommitdiff
path: root/src/commonMain/kotlin/net/taler/wallet/kotlin/crypto/Planchet.kt
blob: 8f4fb987b08e2af557a74bcd2055280b4ab5dcc7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package net.taler.wallet.kotlin.crypto

import net.taler.wallet.kotlin.Amount
import net.taler.wallet.kotlin.Base32Crockford

internal class Planchet(private val crypto: Crypto) {

    data class CreationRequest(
        val value: Amount,
        val feeWithdraw: Amount,
        val denomPub: String,
        val reservePub: String,
        val reservePriv: String
    )

    data class CreationResult(
        val coinPub: String,
        val coinPriv: String,
        val reservePub: String,
        val denomPubHash: String,
        val denomPub: String,
        val blindingKey: String,
        val withdrawSig: String,
        val coinEv: String,
        val coinValue: Amount,
        val coinEvHash: String
    )

    internal fun create(req: CreationRequest, coinKeyPair: EddsaKeyPair, blindingFactor: ByteArray): CreationResult {
        val reservePub = Base32Crockford.decode(req.reservePub)
        val reservePriv = Base32Crockford.decode(req.reservePriv)
        val denomPub = Base32Crockford.decode(req.denomPub)
        val coinPubHash = crypto.sha512(coinKeyPair.publicKey)
        val ev = crypto.rsaBlind(coinPubHash, blindingFactor, denomPub)
        val amountWithFee = req.value + req.feeWithdraw
        val denomPubHash = crypto.sha512(denomPub)
        val evHash = crypto.sha512(ev)

        val withdrawRequest = Signature.PurposeBuilder(Signature.RESERVE_WITHDRAW)
            .put(reservePub)
            .put(amountWithFee.toByteArray())
            .put(req.feeWithdraw.toByteArray())
            .put(denomPubHash)
            .put(evHash)
            .build()

        val sig = crypto.eddsaSign(withdrawRequest, reservePriv)
        return CreationResult(
            blindingKey = Base32Crockford.encode(blindingFactor),
            coinEv = Base32Crockford.encode(ev),
            coinPriv = Base32Crockford.encode(coinKeyPair.privateKey),
            coinPub = Base32Crockford.encode(coinKeyPair.publicKey),
            coinValue = req.value,
            denomPub = req.denomPub,
            denomPubHash = Base32Crockford.encode(denomPubHash),
            reservePub = req.reservePub,
            withdrawSig = Base32Crockford.encode(sig),
            coinEvHash = Base32Crockford.encode(evHash)
        )
    }

    /**
     * Create a pre-coin ([Planchet]) of the given [CreationRequest].
     */
    fun create(req: CreationRequest): CreationResult {
        val coinKeyPair = crypto.createEddsaKeyPair()
        val blindingFactor = crypto.getRandomBytes(32)
        return create(req, coinKeyPair, blindingFactor)
    }

}