/
utxo.go
281 lines (233 loc) · 9.55 KB
/
utxo.go
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
package v1
import (
"encoding/binary"
"encoding/hex"
"encoding/json"
"strconv"
"strings"
"github.com/labstack/echo/v4"
"github.com/pkg/errors"
"github.com/gohornet/hornet/pkg/model/milestone"
"github.com/gohornet/hornet/pkg/model/utxo"
"github.com/gohornet/hornet/pkg/restapi"
"github.com/iotaledger/hive.go/kvstore"
"github.com/iotaledger/hive.go/serializer"
iotago "github.com/iotaledger/iota.go/v2"
)
func NewOutputResponse(output *utxo.Output, ledgerIndex milestone.Index) (*OutputResponse, error) {
var rawOutput iotago.Output
switch output.OutputType() {
case iotago.OutputSigLockedSingleOutput:
rawOutput = &iotago.SigLockedSingleOutput{
Address: output.Address(),
Amount: output.Amount(),
}
case iotago.OutputSigLockedDustAllowanceOutput:
rawOutput = &iotago.SigLockedDustAllowanceOutput{
Address: output.Address(),
Amount: output.Amount(),
}
default:
return nil, errors.WithMessagef(echo.ErrInternalServerError, "unsupported output type: %d", output.OutputType())
}
rawOutputJSON, err := rawOutput.MarshalJSON()
if err != nil {
return nil, errors.WithMessagef(echo.ErrInternalServerError, "marshaling output failed: %s, error: %s", output.OutputID().ToHex(), err)
}
rawRawOutputJSON := json.RawMessage(rawOutputJSON)
return &OutputResponse{
MessageID: output.MessageID().ToHex(),
TransactionID: hex.EncodeToString(output.OutputID()[:iotago.TransactionIDLength]),
Spent: false,
OutputIndex: binary.LittleEndian.Uint16(output.OutputID()[iotago.TransactionIDLength : iotago.TransactionIDLength+serializer.UInt16ByteSize]),
RawOutput: &rawRawOutputJSON,
LedgerIndex: ledgerIndex,
}, nil
}
func NewSpentResponse(spent *utxo.Spent, ledgerIndex milestone.Index) (*OutputResponse, error) {
response, err := NewOutputResponse(spent.Output(), ledgerIndex)
if err != nil {
return nil, err
}
response.Spent = true
response.MilestoneIndexSpent = spent.ConfirmationIndex()
response.TransactionIDSpent = hex.EncodeToString(spent.TargetTransactionID()[:])
return response, nil
}
func outputByID(c echo.Context) (*OutputResponse, error) {
outputID, err := restapi.ParseOutputIDParam(c)
if err != nil {
return nil, err
}
// we need to lock the ledger here to have the correct index for unspent info of the output.
deps.UTXOManager.ReadLockLedger()
defer deps.UTXOManager.ReadUnlockLedger()
ledgerIndex, err := deps.UTXOManager.ReadLedgerIndexWithoutLocking()
if err != nil {
return nil, errors.WithMessagef(echo.ErrInternalServerError, "reading output failed: %s, error: %s", outputID.ToHex(), err)
}
output, err := deps.UTXOManager.ReadOutputByOutputIDWithoutLocking(outputID)
if err != nil {
if errors.Is(err, kvstore.ErrKeyNotFound) {
return nil, errors.WithMessagef(echo.ErrNotFound, "output not found: %s", outputID.ToHex())
}
return nil, errors.WithMessagef(echo.ErrInternalServerError, "reading output failed: %s, error: %s", outputID.ToHex(), err)
}
isUnspent, err := deps.UTXOManager.IsOutputUnspentWithoutLocking(output)
if err != nil {
return nil, errors.WithMessagef(echo.ErrInternalServerError, "reading spent status failed: %s, error: %s", outputID.ToHex(), err)
}
if isUnspent {
return NewOutputResponse(output, ledgerIndex)
}
spent, err := deps.UTXOManager.ReadSpentForOutputWithoutLocking(output)
if err != nil {
if errors.Is(err, kvstore.ErrKeyNotFound) {
return nil, errors.WithMessagef(echo.ErrNotFound, "output not found: %s", outputID.ToHex())
}
return nil, errors.WithMessagef(echo.ErrInternalServerError, "reading output failed: %s, error: %s", outputID.ToHex(), err)
}
return NewSpentResponse(spent, ledgerIndex)
}
func ed25519Balance(address *iotago.Ed25519Address) (*addressBalanceResponse, error) {
balance, dustAllowed, ledgerIndex, err := deps.UTXOManager.AddressBalance(address)
if err != nil {
return nil, errors.WithMessagef(echo.ErrInternalServerError, "reading address balance failed: %s, error: %s", address, err)
}
return &addressBalanceResponse{
AddressType: address.Type(),
Address: address.String(),
Balance: balance,
DustAllowed: dustAllowed,
LedgerIndex: ledgerIndex,
}, nil
}
func balanceByBech32Address(c echo.Context) (*addressBalanceResponse, error) {
if !deps.SyncManager.WaitForNodeSynced(waitForNodeSyncedTimeout) {
return nil, errors.WithMessage(echo.ErrServiceUnavailable, "node is not synced")
}
bech32Address, err := restapi.ParseBech32AddressParam(c, deps.Bech32HRP)
if err != nil {
return nil, err
}
switch address := bech32Address.(type) {
case *iotago.Ed25519Address:
return ed25519Balance(address)
default:
return nil, errors.WithMessagef(restapi.ErrInvalidParameter, "invalid address: %s, error: unknown address type", address.String())
}
}
func balanceByEd25519Address(c echo.Context) (*addressBalanceResponse, error) {
if !deps.SyncManager.WaitForNodeSynced(waitForNodeSyncedTimeout) {
return nil, errors.WithMessage(echo.ErrServiceUnavailable, "node is not synced")
}
address, err := restapi.ParseEd25519AddressParam(c)
if err != nil {
return nil, err
}
return ed25519Balance(address)
}
func outputsResponse(address iotago.Address, includeSpent bool, filterType *iotago.OutputType) (*addressOutputsResponse, error) {
maxResults := deps.RestAPILimitsMaxResults
opts := []utxo.UTXOIterateOption{
utxo.FilterAddress(address),
utxo.ReadLockLedger(false),
}
if filterType != nil {
opts = append(opts, utxo.FilterOutputType(*filterType))
}
// we need to lock the ledger here to have the same index for unspent and spent outputs.
deps.UTXOManager.ReadLockLedger()
defer deps.UTXOManager.ReadUnlockLedger()
ledgerIndex, err := deps.UTXOManager.ReadLedgerIndexWithoutLocking()
if err != nil {
return nil, errors.WithMessagef(echo.ErrInternalServerError, "reading unspent outputs failed: %s, error: %s", address, err)
}
unspentOutputs, err := deps.UTXOManager.UnspentOutputs(append(opts, utxo.MaxResultCount(maxResults))...)
if err != nil {
return nil, errors.WithMessagef(echo.ErrInternalServerError, "reading unspent outputs failed: %s, error: %s", address, err)
}
outputIDs := make([]string, len(unspentOutputs))
for i, unspentOutput := range unspentOutputs {
outputIDs[i] = unspentOutput.OutputID().ToHex()
}
if includeSpent && maxResults-len(outputIDs) > 0 {
spents, err := deps.UTXOManager.SpentOutputs(append(opts, utxo.MaxResultCount(maxResults-len(outputIDs)))...)
if err != nil {
return nil, errors.WithMessagef(echo.ErrInternalServerError, "reading spent outputs failed: %s, error: %s", address, err)
}
outputIDsSpent := make([]string, len(spents))
for i, spent := range spents {
outputIDsSpent[i] = spent.OutputID().ToHex()
}
outputIDs = append(outputIDs, outputIDsSpent...)
}
return &addressOutputsResponse{
AddressType: address.Type(),
Address: address.String(),
MaxResults: uint32(maxResults),
Count: uint32(len(outputIDs)),
OutputIDs: outputIDs,
LedgerIndex: ledgerIndex,
}, nil
}
func outputsIDsByBech32Address(c echo.Context) (*addressOutputsResponse, error) {
if !deps.SyncManager.WaitForNodeSynced(waitForNodeSyncedTimeout) {
return nil, errors.WithMessage(echo.ErrServiceUnavailable, "node is not synced")
}
// error is ignored because it returns false in case it can't be parsed
includeSpent, _ := strconv.ParseBool(strings.ToLower(c.QueryParam("include-spent")))
typeParam := strings.ToLower(c.QueryParam("type"))
var filteredType *iotago.OutputType
if len(typeParam) > 0 {
outputTypeInt, err := strconv.ParseInt(typeParam, 10, 32)
if err != nil {
return nil, errors.WithMessagef(restapi.ErrInvalidParameter, "invalid type: %s, error: unknown output type", typeParam)
}
outputType := iotago.OutputType(outputTypeInt)
if outputType != iotago.OutputSigLockedSingleOutput && outputType != iotago.OutputSigLockedDustAllowanceOutput {
return nil, errors.WithMessagef(restapi.ErrInvalidParameter, "invalid type: %s, error: unknown output type", typeParam)
}
filteredType = &outputType
}
bech32Address, err := restapi.ParseBech32AddressParam(c, deps.Bech32HRP)
if err != nil {
return nil, err
}
return outputsResponse(bech32Address, includeSpent, filteredType)
}
func outputsIDsByEd25519Address(c echo.Context) (*addressOutputsResponse, error) {
if !deps.SyncManager.WaitForNodeSynced(waitForNodeSyncedTimeout) {
return nil, errors.WithMessage(echo.ErrServiceUnavailable, "node is not synced")
}
// error is ignored because it returns false in case it can't be parsed
includeSpent, _ := strconv.ParseBool(strings.ToLower(c.QueryParam("include-spent")))
var filteredType *iotago.OutputType
typeParam := strings.ToLower(c.QueryParam("type"))
if len(typeParam) > 0 {
outputTypeInt, err := strconv.ParseInt(typeParam, 10, 32)
if err != nil {
return nil, errors.WithMessagef(restapi.ErrInvalidParameter, "invalid type: %s, error: unknown output type", typeParam)
}
outputType := iotago.OutputType(outputTypeInt)
if outputType != iotago.OutputSigLockedSingleOutput && outputType != iotago.OutputSigLockedDustAllowanceOutput {
return nil, errors.WithMessagef(restapi.ErrInvalidParameter, "invalid type: %s, error: unknown output type", typeParam)
}
filteredType = &outputType
}
address, err := restapi.ParseEd25519AddressParam(c)
if err != nil {
return nil, err
}
return outputsResponse(address, includeSpent, filteredType)
}
func treasury(_ echo.Context) (*treasuryResponse, error) {
treasuryOutput, err := deps.UTXOManager.UnspentTreasuryOutputWithoutLocking()
if err != nil {
return nil, err
}
return &treasuryResponse{
MilestoneID: hex.EncodeToString(treasuryOutput.MilestoneID[:]),
Amount: treasuryOutput.Amount,
}, nil
}