/
Transaction.scala
376 lines (333 loc) · 11.6 KB
/
Transaction.scala
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
// Copyright 2018 The Alephium Authors
// This file is part of the alephium project.
//
// The library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the library. If not, see <http://www.gnu.org/licenses/>.
package org.alephium.protocol.model
import akka.util.ByteString
import org.alephium.crypto.MerkleHashable
import org.alephium.protocol._
import org.alephium.protocol.config.{ConsensusConfigs, GroupConfig, NetworkConfig}
import org.alephium.protocol.mining.Emission
import org.alephium.protocol.model.Transaction.MerkelTx
import org.alephium.protocol.vm.LockupScript
import org.alephium.serde._
import org.alephium.util.{AVector, Duration, Math, TimeStamp, U256}
sealed trait TransactionAbstract {
def unsigned: UnsignedTransaction
def inputSignatures: AVector[Signature]
def scriptSignatures: AVector[Signature]
def id: TransactionId = unsigned.id
// this might only works for validated tx
def fromGroup(implicit config: GroupConfig): GroupIndex = unsigned.fromGroup
// this might only works for validated tx
def toGroup(implicit config: GroupConfig): GroupIndex = unsigned.toGroup
// this might only works for validated tx
def chainIndex(implicit config: GroupConfig): ChainIndex = ChainIndex(fromGroup, toGroup)
def gasFeeUnsafe: U256 = unsigned.gasPrice * unsigned.gasAmount
def outputsLength: Int
def getOutput(index: Int): TxOutput
@inline
def fixedOutputRefs: AVector[AssetOutputRef] = {
unsigned.fixedOutputRefs
}
def isEntryMethodPayable: Boolean = unsigned.scriptOpt.exists(_.entryMethod.usePreapprovedAssets)
}
final case class Transaction(
unsigned: UnsignedTransaction,
scriptExecutionOk: Boolean,
contractInputs: AVector[ContractOutputRef],
generatedOutputs: AVector[TxOutput],
inputSignatures: AVector[Signature],
scriptSignatures: AVector[Signature]
) extends TransactionAbstract
with MerkleHashable[Hash]
with SerializationCache {
def toMerkleTx: MerkelTx =
MerkelTx(
id,
scriptExecutionOk,
contractInputs,
generatedOutputs,
inputSignatures,
scriptSignatures
)
def merkleHash: Hash = Hash.hash(serialize(toMerkleTx))
def allOutputs: AVector[TxOutput] = unsigned.fixedOutputs.as[TxOutput] ++ generatedOutputs
def allInputRefs: AVector[TxOutputRef] =
unsigned.inputs.map[TxOutputRef](_.outputRef) ++ contractInputs
def inputsLength: Int = unsigned.inputs.length + contractInputs.length
def outputsLength: Int = unsigned.fixedOutputs.length + generatedOutputs.length
def getOutput(index: Int): TxOutput = {
assume(index >= 0 && index < outputsLength)
if (index < unsigned.fixedOutputs.length) {
unsigned.fixedOutputs(index)
} else {
generatedOutputs(index - unsigned.fixedOutputs.length)
}
}
lazy val outputRefs: AVector[TxOutputRef] = {
AVector.tabulate(outputsLength) { outputIndex =>
if (outputIndex < unsigned.fixedOutputs.length) {
unsigned.fixedOutputRefs(outputIndex)
} else {
val output = generatedOutputs(outputIndex - unsigned.fixedOutputs.length)
TxOutputRef.from(id, outputIndex, output)
}
}
}
lazy val attoAlphAmountInOutputs: Option[U256] = {
val sum1Opt =
unsigned.fixedOutputs
.foldE(U256.Zero)((sum, output) => sum.add(output.amount).toRight(()))
.toOption
val sum2Opt =
generatedOutputs
.foldE(U256.Zero)((sum, output) => sum.add(output.amount).toRight(()))
.toOption
for {
sum1 <- sum1Opt
sum2 <- sum2Opt
sum <- sum1.add(sum2)
} yield sum
}
def toTemplate: TransactionTemplate =
TransactionTemplate(unsigned, inputSignatures, scriptSignatures)
}
object Transaction {
private val _serde: Serde[Transaction] =
Serde.forProduct6(
Transaction.apply,
t =>
(
t.unsigned,
t.scriptExecutionOk,
t.contractInputs,
t.generatedOutputs,
t.inputSignatures,
t.scriptSignatures
)
)
implicit val serde: Serde[Transaction] = SerializationCache.cachedSerde(_serde)
def from(
inputs: AVector[TxInput],
outputs: AVector[AssetOutput],
generatedOutputs: AVector[TxOutput],
privateKey: PrivateKey
)(implicit networkConfig: NetworkConfig): Transaction = {
from(UnsignedTransaction(inputs, outputs), generatedOutputs, privateKey)
}
def from(
inputs: AVector[TxInput],
outputs: AVector[AssetOutput],
privateKey: PrivateKey
)(implicit networkConfig: NetworkConfig): Transaction = {
from(inputs, outputs, AVector.empty, privateKey)
}
def from(
inputs: AVector[TxInput],
outputs: AVector[AssetOutput],
inputSignatures: AVector[Signature]
)(implicit networkConfig: NetworkConfig): Transaction = {
Transaction(
UnsignedTransaction(inputs, outputs),
scriptExecutionOk = true,
contractInputs = AVector.empty,
generatedOutputs = AVector.empty,
inputSignatures,
scriptSignatures = AVector.empty
)
}
def from(
inputs: AVector[TxInput],
outputs: AVector[AssetOutput],
generatedOutputs: AVector[TxOutput],
inputSignatures: AVector[Signature]
)(implicit networkConfig: NetworkConfig): Transaction = {
Transaction(
UnsignedTransaction(inputs, outputs),
scriptExecutionOk = true,
contractInputs = AVector.empty,
generatedOutputs,
inputSignatures,
scriptSignatures = AVector.empty
)
}
def from(unsigned: UnsignedTransaction, privateKey: PrivateKey): Transaction = {
from(unsigned, AVector.empty[TxOutput], privateKey)
}
def from(
unsigned: UnsignedTransaction,
generatedOutputs: AVector[TxOutput],
privateKey: PrivateKey
): Transaction = {
val signature = SignatureSchema.sign(unsigned.id, privateKey)
Transaction(
unsigned,
scriptExecutionOk = true,
contractInputs = AVector.empty,
generatedOutputs,
AVector(signature),
scriptSignatures = AVector.empty
)
}
def from(
unsigned: UnsignedTransaction,
contractInputs: AVector[ContractOutputRef],
generatedOutputs: AVector[TxOutput],
privateKey: PrivateKey
): Transaction = {
val signature = SignatureSchema.sign(unsigned.id, privateKey)
Transaction(
unsigned,
scriptExecutionOk = true,
contractInputs,
generatedOutputs,
AVector(signature),
scriptSignatures = AVector.empty
)
}
def from(unsigned: UnsignedTransaction, inputSignatures: AVector[Signature]): Transaction = {
Transaction(
unsigned,
scriptExecutionOk = true,
contractInputs = AVector.empty,
generatedOutputs = AVector.empty,
inputSignatures,
scriptSignatures = AVector.empty
)
}
def totalReward(gasFee: U256, miningReward: U256, hardFork: HardFork): U256 = {
if (hardFork.isLemanEnabled()) {
miningReward
} else {
totalRewardPreLeman(gasFee, miningReward)
}
}
// PoLW burning is not considered
@inline def totalRewardPreLeman(gasFee: U256, miningReward: U256): U256 = {
val threshold = Math.max(miningReward, ALPH.oneAlph)
val gasReward = gasFee.divUnsafe(U256.Two)
if (gasReward >= threshold) {
miningReward.addUnsafe(threshold)
} else {
miningReward.addUnsafe(gasReward)
}
}
// scalastyle:off parameter.number
@SuppressWarnings(
Array("org.wartremover.warts.AsInstanceOf", "org.wartremover.warts.DefaultArguments")
)
def powCoinbaseForTest(
chainIndex: ChainIndex,
txs: AVector[Transaction],
lockupScript: LockupScript.Asset,
target: Target,
blockTs: TimeStamp,
uncles: AVector[SelectedGhostUncle],
minerData: ByteString = ByteString.empty
)(implicit consensusConfigs: ConsensusConfigs, networkConfig: NetworkConfig): Transaction = {
val consensusConfig = consensusConfigs.getConsensusConfig(blockTs)
val gasFee = txs.fold(U256.Zero)(_ addUnsafe _.gasFeeUnsafe)
val powReward = consensusConfig.emission
.reward(target, blockTs, ALPH.LaunchTimestamp)
.asInstanceOf[Emission.PoW]
val rewardAmount = Coinbase.powMiningReward(gasFee, powReward, blockTs)
powCoinbase(chainIndex, rewardAmount, lockupScript, minerData, blockTs, uncles)
}
// scalastyle:on parameter.number
def powCoinbase(
chainIndex: ChainIndex,
rewardAmount: U256,
lockupScript: LockupScript.Asset,
blockTs: TimeStamp,
uncles: AVector[SelectedGhostUncle]
)(implicit networkConfig: NetworkConfig): Transaction = {
powCoinbase(chainIndex, rewardAmount, lockupScript, ByteString.empty, blockTs, uncles)
}
def powCoinbase(
chainIndex: ChainIndex,
rewardAmount: U256,
lockupScript: LockupScript.Asset,
minerData: ByteString,
blockTs: TimeStamp,
uncles: AVector[SelectedGhostUncle]
)(implicit networkConfig: NetworkConfig): Transaction = {
Coinbase.buildPoWCoinbase(chainIndex, rewardAmount, lockupScript, minerData, blockTs, uncles)
}
def genesis(
balances: AVector[(LockupScript.Asset, U256, Duration)],
noPreMineProof: ByteString
)(implicit networkConfig: NetworkConfig): Transaction = {
val outputs = balances.mapWithIndex[AssetOutput] {
case ((lockupScript, value, lockupDuration), index) =>
val txData = if (index == 0) noPreMineProof else ByteString.empty
TxOutput.genesis(value, lockupScript, lockupDuration, txData)
}
val unsigned = UnsignedTransaction(inputs = AVector.empty, fixedOutputs = outputs)
Transaction(
unsigned,
scriptExecutionOk = true,
contractInputs = AVector.empty,
generatedOutputs = AVector.empty,
inputSignatures = AVector.empty,
scriptSignatures = AVector.empty
)
}
final private[model] case class MerkelTx(
id: TransactionId,
scriptExecutionOk: Boolean,
contractInputs: AVector[ContractOutputRef],
generatedOutputs: AVector[TxOutput],
inputSignatures: AVector[Signature],
scriptSignatures: AVector[Signature]
)
object MerkelTx {
implicit val serde: Serde[MerkelTx] = Serde.forProduct6(
MerkelTx.apply,
t =>
(
t.id,
t.scriptExecutionOk,
t.contractInputs,
t.generatedOutputs,
t.inputSignatures,
t.scriptSignatures
)
)
}
}
final case class TransactionTemplate(
unsigned: UnsignedTransaction,
inputSignatures: AVector[Signature],
scriptSignatures: AVector[Signature]
) extends TransactionAbstract
with SerializationCache {
override def outputsLength: Int = unsigned.fixedOutputs.length
override def getOutput(index: Int): TxOutput = unsigned.fixedOutputs(index)
}
object TransactionTemplate {
private val _serde: Serde[TransactionTemplate] = Serde.forProduct3(
TransactionTemplate.apply,
t => (t.unsigned, t.inputSignatures, t.scriptSignatures)
)
implicit val serde: Serde[TransactionTemplate] = SerializationCache.cachedSerde(_serde)
def from(unsigned: UnsignedTransaction, privateKey: PrivateKey): TransactionTemplate = {
val signature = SignatureSchema.sign(unsigned.id, privateKey)
TransactionTemplate(
unsigned,
AVector(signature),
scriptSignatures = AVector.empty
)
}
}