-
Notifications
You must be signed in to change notification settings - Fork 146
Expand file tree
/
Copy pathUser.cpp
More file actions
627 lines (531 loc) · 27.4 KB
/
User.cpp
File metadata and controls
627 lines (531 loc) · 27.4 KB
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
// UTT Client API
//
// Copyright (c) 2020-2022 VMware, Inc. All Rights Reserved.
//
// This product is licensed to you under the Apache 2.0 license (the "License").
// You may not use this product except in compliance with the Apache 2.0
// License.
//
// This product may include a number of subcomponents with separate copyright
// notices and license terms. Your use of these subcomponents is subject to the
// terms and conditions of the sub-component's license, as noted in the LICENSE
// file.
#include "utt-client-api/User.hpp"
// libutt
#include <utt/DataUtils.hpp>
// libutt new interface
#include <UTTParams.hpp>
#include <coin.hpp>
#include <client.hpp>
#include <config.hpp>
#include <budget.hpp>
#include <mint.hpp>
#include <burn.hpp>
#include <transaction.hpp>
#include <serialization.hpp>
#include "utt-client-api/PickCoins.hpp"
using namespace libutt;
#define logdbg_user logdbg << ((pImpl_->client_) ? pImpl_->client_->getPid() : "!!!uninitialized user!!!") << ' '
namespace {
std::string dbgPrintCoins(const std::vector<libutt::api::Coin>& coins) {
if (coins.empty()) return "[empty]";
std::stringstream ss;
ss << '[';
for (const auto& coin : coins) {
ss << "type:" << (coin.getType() == libutt::api::Coin::Type::Budget ? "budget" : "normal");
ss << "|val:" << coin.getVal();
ss << "|exp:" << coin.getExpDate();
ss << "|null:" << coin.getNullifier() << ", ";
}
ss << ']';
return ss.str();
}
std::string dbgPrintRecipients(const std::vector<std::tuple<std::string, uint64_t>>& recips) {
if (recips.empty()) return "[empty]";
std::stringstream ss;
ss << '[';
for (const auto& recip : recips) {
ss << std::get<0>(recip) << ": " << std::get<1>(recip) << ", ";
}
ss << ']';
return ss.str();
}
} // namespace
namespace utt::client {
struct User::Impl {
utt::Transaction createTx_Burn(const libutt::api::Coin& coin);
utt::Transaction createTx_Self1to2(const libutt::api::Coin& coin, uint64_t amount);
utt::Transaction createTx_Self2to1(const std::vector<libutt::api::Coin>& coins);
utt::Transaction createTx_Self2to2(const std::vector<libutt::api::Coin>& coins, uint64_t amount);
utt::Transaction createTx_1to1(const libutt::api::Coin& coin, const std::string& userId, const std::string& pk);
utt::Transaction createTx_1to2(const libutt::api::Coin& coin,
uint64_t amount,
const std::string& userId,
const std::string& pk);
utt::Transaction createTx_2to1(const std::vector<libutt::api::Coin>& coins,
const std::string& userId,
const std::string& pk);
utt::Transaction createTx_2to2(const std::vector<libutt::api::Coin>& coins,
uint64_t amount,
const std::string& userId,
const std::string& pk);
libutt::RSAEncryptor createRsaEncryptorForTransferToOther(const std::string& otherUserId, const std::string& otherPk);
std::string sk_; // User's secret key
std::string pk_; // User's public key
libutt::api::types::CurvePoint s1_; // User's secret part of the PRF key
libutt::api::UTTParams params_;
std::unique_ptr<libutt::api::Client> client_; // User's credentials
std::unique_ptr<libutt::RSAEncryptor>
selfTxEncryptor_; // Encryptor with own's public key for self transactions (computed once for convenience)
std::unordered_map<std::string, libutt::api::Coin> coins_; // User's unspent UTT coins (tokens)
std::optional<libutt::api::Coin> budgetCoin_; // User's current UTT budget coin (token)
std::set<std::string> budgetNullifiers_;
std::shared_ptr<IStorage> storage_;
bool is_registered_ = false;
};
utt::Transaction User::Impl::createTx_Burn(const libutt::api::Coin& coin) {
logdbg << client_->getPid() << " creates burn tx with input coins: " << dbgPrintCoins({coin}) << endl;
utt::Transaction tx;
tx.type_ = utt::Transaction::Type::Burn;
auto burn = libutt::api::operations::Burn(params_, *client_, coin);
tx.data_ = libutt::api::serialize<libutt::api::operations::Burn>(burn);
return tx;
}
utt::Transaction User::Impl::createTx_Self1to2(const libutt::api::Coin& coin, uint64_t amount) {
std::vector<std::tuple<std::string, uint64_t>> recip;
recip.emplace_back(client_->getPid(), amount);
recip.emplace_back(client_->getPid(), coin.getVal() - amount);
logdbg << client_->getPid() << " creates self-split tx with input coins: " << dbgPrintCoins({coin})
<< " and recipients: " << dbgPrintRecipients(recip) << endl;
auto uttTx = libutt::api::operations::Transaction(params_, *client_, {coin}, std::nullopt, recip, *selfTxEncryptor_);
utt::Transaction tx;
tx.type_ = utt::Transaction::Type::Transfer;
tx.data_ = libutt::api::serialize<libutt::api::operations::Transaction>(uttTx);
tx.numOutputs_ = uttTx.getNumOfOutputCoins();
return tx;
}
utt::Transaction User::Impl::createTx_Self2to1(const std::vector<libutt::api::Coin>& coins) {
std::vector<std::tuple<std::string, uint64_t>> recip;
recip.emplace_back(client_->getPid(), coins[0].getVal() + coins[1].getVal());
logdbg << client_->getPid() << " creates self-merge with input coins: " << dbgPrintCoins(coins)
<< " and recipients: " << dbgPrintRecipients(recip) << endl;
auto uttTx = libutt::api::operations::Transaction(params_, *client_, coins, std::nullopt, recip, *selfTxEncryptor_);
utt::Transaction tx;
tx.type_ = utt::Transaction::Type::Transfer;
tx.data_ = libutt::api::serialize<libutt::api::operations::Transaction>(uttTx);
tx.numOutputs_ = uttTx.getNumOfOutputCoins();
return tx;
}
utt::Transaction User::Impl::createTx_Self2to2(const std::vector<libutt::api::Coin>& coins, uint64_t amount) {
std::vector<std::tuple<std::string, uint64_t>> recip;
recip.emplace_back(client_->getPid(), amount);
recip.emplace_back(client_->getPid(), (coins[0].getVal() + coins[1].getVal()) - amount);
logdbg << client_->getPid() << " creates 2-to-2 self-split with input coins: " << dbgPrintCoins(coins)
<< " and recipients: " << dbgPrintRecipients(recip) << endl;
auto uttTx = libutt::api::operations::Transaction(params_, *client_, coins, std::nullopt, recip, *selfTxEncryptor_);
utt::Transaction tx;
tx.type_ = utt::Transaction::Type::Transfer;
tx.data_ = libutt::api::serialize<libutt::api::operations::Transaction>(uttTx);
tx.numOutputs_ = uttTx.getNumOfOutputCoins();
return tx;
}
utt::Transaction User::Impl::createTx_1to1(const libutt::api::Coin& coin,
const std::string& userId,
const std::string& pk) {
std::vector<std::tuple<std::string, uint64_t>> recip;
recip.emplace_back(userId, coin.getVal());
logdbg << client_->getPid() << " creates 1-to-1 transfer with input coins: " << dbgPrintCoins({coin})
<< " and recipients: " << dbgPrintRecipients(recip) << endl;
auto encryptor = createRsaEncryptorForTransferToOther(userId, pk);
auto uttTx = libutt::api::operations::Transaction(params_, *client_, {coin}, budgetCoin_, recip, encryptor);
utt::Transaction tx;
tx.type_ = utt::Transaction::Type::Transfer;
tx.data_ = libutt::api::serialize<libutt::api::operations::Transaction>(uttTx);
tx.numOutputs_ = uttTx.getNumOfOutputCoins();
return tx;
}
utt::Transaction User::Impl::createTx_1to2(const libutt::api::Coin& coin,
uint64_t amount,
const std::string& userId,
const std::string& pk) {
std::vector<std::tuple<std::string, uint64_t>> recip;
recip.emplace_back(userId, amount);
recip.emplace_back(client_->getPid(), coin.getVal() - amount);
logdbg << client_->getPid() << " creates 1-to-2 transfer with input coins: " << dbgPrintCoins({coin})
<< " and recipients: " << dbgPrintRecipients(recip) << endl;
auto encryptor = createRsaEncryptorForTransferToOther(userId, pk);
auto uttTx = libutt::api::operations::Transaction(params_, *client_, {coin}, budgetCoin_, recip, encryptor);
utt::Transaction tx;
tx.type_ = utt::Transaction::Type::Transfer;
tx.data_ = libutt::api::serialize<libutt::api::operations::Transaction>(uttTx);
tx.numOutputs_ = uttTx.getNumOfOutputCoins();
return tx;
}
utt::Transaction User::Impl::createTx_2to1(const std::vector<libutt::api::Coin>& coins,
const std::string& userId,
const std::string& pk) {
std::vector<std::tuple<std::string, uint64_t>> recip;
recip.emplace_back(userId, coins[0].getVal() + coins[1].getVal());
logdbg << client_->getPid() << "creates 2-to-1 transfer with input coins: " << dbgPrintCoins(coins)
<< " and recipients: " << dbgPrintRecipients(recip) << endl;
auto encryptor = createRsaEncryptorForTransferToOther(userId, pk);
auto uttTx = libutt::api::operations::Transaction(params_, *client_, coins, budgetCoin_, recip, encryptor);
utt::Transaction tx;
tx.type_ = utt::Transaction::Type::Transfer;
tx.data_ = libutt::api::serialize<libutt::api::operations::Transaction>(uttTx);
tx.numOutputs_ = uttTx.getNumOfOutputCoins();
return tx;
}
utt::Transaction User::Impl::createTx_2to2(const std::vector<libutt::api::Coin>& coins,
uint64_t amount,
const std::string& userId,
const std::string& pk) {
std::vector<std::tuple<std::string, uint64_t>> recip;
recip.emplace_back(userId, amount);
recip.emplace_back(client_->getPid(), (coins[0].getVal() + coins[1].getVal()) - amount);
logdbg << client_->getPid() << " creates 2-to-2 transfer with input coins: " << dbgPrintCoins(coins)
<< " and recipients: " << dbgPrintRecipients(recip) << endl;
auto encryptor = createRsaEncryptorForTransferToOther(userId, pk);
auto uttTx = libutt::api::operations::Transaction(params_, *client_, coins, budgetCoin_, recip, encryptor);
utt::Transaction tx;
tx.type_ = utt::Transaction::Type::Transfer;
tx.data_ = libutt::api::serialize<libutt::api::operations::Transaction>(uttTx);
tx.numOutputs_ = uttTx.getNumOfOutputCoins();
return tx;
}
libutt::RSAEncryptor User::Impl::createRsaEncryptorForTransferToOther(const std::string& otherUserId,
const std::string& otherPk) {
std::map<std::string, std::string> creds;
creds.emplace(client_->getPid(), pk_); // Own credentials used for budget coin and change output
creds.emplace(otherUserId, otherPk); // Other user credentials
return libutt::RSAEncryptor{creds};
}
std::unique_ptr<User> User::createInitial(const std::string& userId,
const PublicConfig& config,
const std::string& private_key,
const std::string& public_key,
std::shared_ptr<IStorage> storage) {
if (userId.empty()) throw std::runtime_error("User id cannot be empty!");
if (config.empty()) throw std::runtime_error("UTT instance public config cannot be empty!");
if (private_key.empty()) throw std::runtime_error("User private key cannot be empty!");
if (public_key.empty()) throw std::runtime_error("User public key cannot be empty!");
auto uttConfig = libutt::api::deserialize<libutt::api::PublicConfig>(config);
auto user = std::make_unique<User>();
user->pImpl_->pk_ = public_key;
user->pImpl_->params_ = uttConfig.getParams();
user->pImpl_->storage_ = storage;
// Create a client object with an RSA based PKI
user->pImpl_->client_.reset(new libutt::api::Client(
userId, uttConfig.getCommitVerificationKey(), uttConfig.getRegistrationVerificationKey(), private_key));
std::map<std::string, std::string> selfTxCredentials{{userId, public_key}};
user->pImpl_->selfTxEncryptor_ = std::make_unique<libutt::RSAEncryptor>(selfTxCredentials);
if (storage->isNewStorage()) {
IStorage::tx_guard g(*storage);
storage->setUserId(userId);
storage->setKeyPair({private_key, public_key});
storage->setUttPublicConfig(uttConfig);
}
return user;
}
std::unique_ptr<User> User::recoverFromStorage(std::shared_ptr<IStorage> storage) {
// First lets create a User object.
if (storage->isNewStorage()) throw std::runtime_error("cannot recover user from non initialized storage");
// As we have atomic transaction on createInitial, we know that if the storage is initiated, all the initial
// information is there
std::string user_id = storage->getUserId();
auto key_pair = storage->getKeyPair();
auto utt_public_config = libutt::api::serialize<libutt::api::PublicConfig>(storage->getUttPublicConfig());
std::unique_ptr<User> user = createInitial(user_id, utt_public_config, key_pair.first, key_pair.second, storage);
/**
* To recover the client we need to perform the following:
* 1. recover registration data (if there is any)
* 2. recover all existing coins
*/
auto s1 = storage->getClientSideSecret();
if (s1.empty()) {
logdbg << "The client has not started registration phase, no additional data to recover" << endl;
return user;
}
user->pImpl_->s1_ = s1;
user->pImpl_->client_->setS1(s1);
// We don't care about recovering rcm1. Its the system responsibility to prevent double registration
auto s2 = storage->getSystemSideSecret();
if (s2.empty()) {
logdbg << "The client has not passed yet the registration phase, no additional data to recover" << endl;
return user;
}
auto rcm_sig = storage->getRcmSignature();
if (rcm_sig.empty()) throw std::runtime_error("s2 exist but rcm signature is empty");
user->pImpl_->client_->setRCMSig(user->pImpl_->params_, s2, rcm_sig);
user->pImpl_->is_registered_ = true;
auto coins = storage->getCoins();
for (const auto& c : coins) {
if (!user->pImpl_->client_->validate(c))
throw std::runtime_error("client has failed to validate its own stored coins");
if (c.getType() == libutt::api::Coin::Normal) {
user->pImpl_->coins_.emplace(c.getNullifier(), c);
} else if (c.getType() == libutt::api::Coin::Budget) {
// Currently the original budget coin and change budget coins would
// be stored in assets.
// Until budget coin pool is supported, use the budget with lowest value
// to stick to current single outstanding budget workflow model
if (user->pImpl_->budgetNullifiers_.size() >= 1) {
if (c.getVal() < user->pImpl_->budgetCoin_.value().getVal()) {
user->pImpl_->budgetCoin_.emplace(c);
//@todo assuming nullifier list is not used except for book keeping
user->pImpl_->budgetNullifiers_.clear();
user->pImpl_->budgetNullifiers_.insert(c.getNullifier());
std::cout << "warn: mutiple budget coins found updating with least value.." << c.getVal() << std::endl;
} else {
std::cout << "warn: ignore budget coins value: " << c.getVal()
<< " use lower value: " << user->pImpl_->budgetCoin_.value().getVal() << std::endl;
}
} else {
user->pImpl_->budgetCoin_.emplace(c);
user->pImpl_->budgetNullifiers_.insert(c.getNullifier());
}
}
}
return user;
}
User::User() : pImpl_{new Impl{}} {}
User::~User() = default;
UserRegistrationInput User::getRegistrationInput() const {
if (!pImpl_->client_) return UserRegistrationInput{}; // Empty
libutt::api::Commitment comm = pImpl_->client_->generateInputRCM();
{
IStorage::tx_guard g(*pImpl_->storage_);
pImpl_->storage_->setClientSideSecret(pImpl_->client_->getS1());
}
return libutt::api::serialize<libutt::api::Commitment>(comm);
}
void User::updateRegistration(const std::string& pk, const RegistrationSig& rs, const S2& s2) {
if (!pImpl_->client_) throw std::runtime_error("User not initialized!");
if (rs.empty() || s2.empty() || pk.empty()) throw std::runtime_error("updateRegistration: invalid arguments!");
if (!(pImpl_->pk_ == pk)) throw std::runtime_error("Public key mismatch!");
// Un-blind the signature
std::vector<libutt::api::types::CurvePoint> randomness = {libutt::Fr::zero().to_words(),
libutt::Fr::zero().to_words()};
auto unblindedSig =
libutt::api::Utils::unblindSignature(pImpl_->params_, libutt::api::Commitment::REGISTRATION, randomness, rs);
if (unblindedSig.empty()) throw std::runtime_error("Failed to unblind reg signature!");
pImpl_->client_->setRCMSig(pImpl_->params_, s2, unblindedSig);
pImpl_->is_registered_ = true;
{
IStorage::tx_guard g(*pImpl_->storage_);
auto rcm = pImpl_->client_->getRcm();
pImpl_->storage_->setRcmSignature(rcm.second);
pImpl_->storage_->setSystemSideSecret(s2);
}
}
void User::updatePrivacyBudget(const PrivacyBudget& budget, const PrivacyBudgetSig& sig) {
if (!pImpl_->client_) throw std::runtime_error("User not initialized!");
logdbg_user << "updating privacy budget" << endl;
auto claimedCoins = pImpl_->client_->claimCoins(libutt::api::deserialize<libutt::api::operations::Budget>(budget),
pImpl_->params_,
std::vector<libutt::api::types::Signature>{sig});
// Expect a single budget token to be claimed by the user
if (claimedCoins.size() != 1) throw std::runtime_error("Expected single budget token!");
if (!pImpl_->client_->validate(claimedCoins[0])) throw std::runtime_error("Invalid initial budget coin!");
auto nullifer = claimedCoins[0].getNullifier();
// std::cout << "Budget nullifer is, hash " << std::hash<std::string>{}(nullifer) << " raw " << nullifer << "\n";
if (pImpl_->budgetNullifiers_.count(claimedCoins[0].getNullifier()) == 1) {
// TODO debug log
return;
}
{
IStorage::tx_guard g(*pImpl_->storage_);
pImpl_->storage_->setCoin(claimedCoins[0]);
}
pImpl_->budgetCoin_ = claimedCoins[0];
logdbg_user << "claimed budget token " << dbgPrintCoins({*pImpl_->budgetCoin_}) << endl;
pImpl_->budgetNullifiers_.insert(claimedCoins[0].getNullifier());
}
uint64_t User::getBalance() const {
uint64_t sum = 0;
for (const auto& [_, coin] : pImpl_->coins_) {
(void)_;
sum += coin.getVal();
}
return sum;
}
bool User::hasRegistrationCommitment() const { return pImpl_->is_registered_; }
uint64_t User::getPrivacyBudget() const { return pImpl_->budgetCoin_ ? pImpl_->budgetCoin_->getVal() : 0; }
const std::string& User::getUserId() const {
static const std::string s_empty;
return pImpl_->client_ ? pImpl_->client_->getPid() : s_empty;
}
const std::string& User::getPK() const { return pImpl_->pk_; }
void User::updateTransferTx(const Transaction& tx, const TxOutputSigs& sigs) {
if (!pImpl_->client_) throw std::runtime_error("User not initialized!");
if (tx.type_ != Transaction::Type::Transfer) throw std::runtime_error("Transfer tx type mismatch!");
auto uttTx = libutt::api::deserialize<libutt::api::operations::Transaction>(tx.data_);
{
IStorage::tx_guard g(*pImpl_->storage_);
// [TODO-UTT] More consistency checks
// If we slash coins we expect to also update our budget coin
// Slash spent coins
for (const auto& null : uttTx.getNullifiers()) {
if (pImpl_->coins_.find(null) != pImpl_->coins_.end()) {
logdbg_user << "slashing spent coin " << dbgPrintCoins({pImpl_->coins_.at(null)}) << endl;
pImpl_->storage_->removeCoin(pImpl_->coins_.at(null));
pImpl_->coins_.erase(null);
}
}
// Claim coins
auto claimedCoins = pImpl_->client_->claimCoins(uttTx, pImpl_->params_, sigs);
bool invalidCoinsInTransfer(false);
for (auto& coin : claimedCoins) {
if (!pImpl_->client_->validate(coin)) {
logdbg_user << "Invalid coin found; coin details: " << dbgPrintCoins({coin}) << endl;
invalidCoinsInTransfer = true;
continue;
}
pImpl_->storage_->setCoin(coin);
if (coin.getType() == libutt::api::Coin::Type::Normal) {
logdbg_user << "claimed normal coin: " << dbgPrintCoins({coin}) << endl;
pImpl_->coins_.emplace(coin.getNullifier(), std::move(coin));
} else if (coin.getType() == libutt::api::Coin::Type::Budget) {
// Replace budget coin
if (coin.getVal() > 0) {
logdbg_user << "claimed budget coin: " << dbgPrintCoins({coin}) << endl;
pImpl_->budgetCoin_ = std::move(coin);
} else {
pImpl_->budgetCoin_ = std::nullopt;
}
}
}
if (invalidCoinsInTransfer) {
throw libutt::api::operations::InvalidCoinsInTransfer("Invalid normal coin(s) in transfer!");
}
}
}
void User::updateMintTx(const Transaction& tx, const TxOutputSig& sig) {
if (!pImpl_->client_) throw std::runtime_error("User not initialized!");
if (tx.type_ != Transaction::Type::Mint) throw std::runtime_error("Mint tx type mismatch!");
auto mint = libutt::api::deserialize<libutt::api::operations::Mint>(tx.data_);
{
IStorage::tx_guard g(*pImpl_->storage_);
if (mint.getRecipentID() != pImpl_->client_->getPid()) {
logdbg_user << "ignores mint transaction for different user: " << mint.getRecipentID() << endl;
} else {
auto claimedCoins =
pImpl_->client_->claimCoins(mint, pImpl_->params_, std::vector<libutt::api::types::Signature>{sig});
// Expect a single token to be claimed by the user
if (claimedCoins.size() != 1) throw std::runtime_error("Expected single coin in mint tx!");
if (!pImpl_->client_->validate(claimedCoins[0])) throw std::runtime_error("Invalid minted coin!");
pImpl_->storage_->setCoin(claimedCoins[0]);
pImpl_->coins_.emplace(claimedCoins[0].getNullifier(), std::move(claimedCoins[0]));
}
}
}
// [TODO-UTT] Do we actually need the whole BurnTx or we can simply use the nullifier to slash?
void User::updateBurnTx(const Transaction& tx) {
if (!pImpl_->client_) throw std::runtime_error("User not initialized!");
if (tx.type_ != Transaction::Type::Burn) throw std::runtime_error("Burn tx type mismatch!");
auto burn = libutt::api::deserialize<libutt::api::operations::Burn>(tx.data_);
{
IStorage::tx_guard g(*pImpl_->storage_);
if (burn.getOwnerPid() != pImpl_->client_->getPid()) {
logdbg_user << "ignores burn tx for different user: " << burn.getOwnerPid() << endl;
} else {
auto nullifier = burn.getNullifier();
if (nullifier.empty()) throw std::runtime_error("Burn tx has empty nullifier!");
if (pImpl_->coins_.find(nullifier) == pImpl_->coins_.end())
throw std::runtime_error("Burned token missing in wallet!");
pImpl_->storage_->removeCoin(pImpl_->coins_.at(nullifier));
pImpl_->coins_.erase(nullifier);
}
}
}
utt::Transaction User::mint(uint64_t amount) const {
std::stringstream ss;
ss << Fr::random_element();
auto randomHash = ss.str();
logdbg_user << "creating a mint tx with random hash: " << randomHash << endl;
auto mint = libutt::api::operations::Mint(randomHash, amount, pImpl_->client_->getPid());
utt::Transaction tx;
tx.type_ = utt::Transaction::Type::Mint;
tx.data_ = libutt::api::serialize<libutt::api::operations::Mint>(mint);
return tx;
}
TxResult User::burn(uint64_t amount) const {
if (!pImpl_->client_) throw std::runtime_error("User not initialized!");
if (amount == 0) throw std::runtime_error("Burn amount must be positive!");
const uint64_t balance = getBalance();
if (balance < amount) throw std::runtime_error("User has insufficient balance!");
auto pickedCoins = PickCoinsPreferExactMatch(pImpl_->coins_, amount);
if (pickedCoins.empty()) throw std::runtime_error("Coin strategy didn't pick any coins!");
if (pickedCoins.size() == 1) {
const auto& coin = pImpl_->coins_.at(pickedCoins[0]);
const uint64_t value = coin.getVal();
if (value < amount) throw std::runtime_error("Coin strategy picked a single insufficient coin!");
if (value == amount) return {pImpl_->createTx_Burn(coin), true /*isFinal*/};
return {pImpl_->createTx_Self1to2(coin, amount), false /*isFinal*/}; // value > payment
} else if (pickedCoins.size() == 2) {
const std::vector<libutt::api::Coin> inputCoins = {pImpl_->coins_.at(pickedCoins[0]),
pImpl_->coins_.at(pickedCoins[1])};
const uint64_t value = inputCoins[0].getVal() + inputCoins[1].getVal();
if (value <= amount) return {pImpl_->createTx_Self2to1(inputCoins), false /*isFinal*/}; // Coin merge
return {pImpl_->createTx_Self2to2(inputCoins, amount), false /*isFinal*/}; // value > payment
} else {
throw std::runtime_error("Coin strategy picked more than two coins!");
}
}
TxResult User::transfer(const std::string& userId, const std::string& destPK, uint64_t amount) const {
if (userId.empty() || destPK.empty() || amount == 0) throw std::runtime_error("Invalid arguments!");
if (!pImpl_->client_) throw std::runtime_error("Uninitialized user!");
const uint64_t balance = getBalance();
if (balance < amount) throw std::runtime_error("User has insufficient balance!");
const size_t budget = getPrivacyBudget();
if (budget < amount) throw std::runtime_error("User has insufficient privacy budget!");
auto pickedCoins = PickCoinsPreferExactMatch(pImpl_->coins_, amount);
if (pickedCoins.empty()) throw std::runtime_error("Coin strategy didn't pick any coins!");
if (pickedCoins.size() == 1) {
const auto& coin = pImpl_->coins_.at(pickedCoins[0]);
const auto value = coin.getVal();
if (value < amount) throw std::runtime_error("Coin strategy picked a single insufficient coin!");
if (value == amount) return {pImpl_->createTx_1to1(coin, userId, destPK), true /*isFinal*/};
return {pImpl_->createTx_1to2(coin, amount, userId, destPK), true /*isFinal*/}; // value > amount
} else if (pickedCoins.size() == 2) {
std::vector<libutt::api::Coin> inputCoins{pImpl_->coins_.at(pickedCoins[0]), pImpl_->coins_.at(pickedCoins[1])};
const auto value = inputCoins[0].getVal() + inputCoins[1].getVal();
if (value < amount) return {pImpl_->createTx_Self2to1(inputCoins), false /*isFinal*/}; // Coin merge
if (value == amount) return {pImpl_->createTx_2to1(inputCoins, userId, destPK), true /*isFinal*/};
return {pImpl_->createTx_2to2(inputCoins, amount, userId, destPK), true /*isFinal*/}; // value > amount
} else {
throw std::runtime_error("Coin strategy picked more than two coins!");
}
}
std::vector<CoinDescriptor> User::getCoinsDescriptors() const {
std::vector<CoinDescriptor> ret;
for (const auto& [nullifier, coin] : pImpl_->coins_) {
ret.push_back({nullifier, coin.getVal()});
}
return ret;
}
void User::debugOutput() const {
std::cout << "------ USER DEBUG OUTPUT START -------------\n";
if (!pImpl_->client_) {
std::cout << "User's libutt::api::client object not initialized!\n";
}
std::cout << "coins: [\n";
auto dbgOutputCoin = [](const libutt::api::Coin& coin) {
std::cout << "type: " << (coin.getType() == libutt::api::Coin::Type::Budget ? "Budget" : "Normal") << ' ';
std::cout << "value: " << coin.getVal() << ' ';
std::cout << "expire: " << coin.getExpDate() << ' ';
std::cout << "null: " << coin.getNullifier() << ' ';
std::cout << "hasSig: " << coin.hasSig() << ' ';
std::cout << '\n';
};
for (const auto& [_, coin] : pImpl_->coins_) {
(void)_;
dbgOutputCoin(coin);
}
std::cout << "]\n";
std::cout << "budget coin: [\n";
if (pImpl_->budgetCoin_) dbgOutputCoin(*pImpl_->budgetCoin_);
std::cout << "]\n";
std::cout << "------ USER DEBUG OUTPUT END -------------\n";
}
} // namespace utt::client