-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathoutside.rs
1470 lines (1292 loc) · 50.2 KB
/
outside.rs
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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::collections::{BTreeMap, VecDeque};
use clvm_traits::ToClvm;
use clvmr::serde::node_from_bytes;
use clvmr::{run_program, Allocator, NodePtr};
use log::debug;
use rand::Rng;
use serde::{Deserialize, Serialize};
use crate::channel_handler::game_handler::chia_dialect;
use crate::channel_handler::types::{
ChannelCoinSpendInfo, ChannelHandlerEnv, ChannelHandlerInitiationData,
ChannelHandlerPrivateKeys, FlatGameStartInfo, GameStartInfo, MoveResult, PotatoSignatures,
PrintableGameStartInfo, ReadableMove,
};
use crate::channel_handler::ChannelHandler;
use crate::common::standard_coin::{private_to_public_key, puzzle_hash_for_pk};
use crate::common::types::{
Aggsig, AllocEncoder, Amount, CoinID, CoinString, Error, GameID, IntoErr, Node, Program,
PublicKey, PuzzleHash, Sha256Input, Spend, SpendBundle, Timeout,
};
use clvm_tools_rs::classic::clvm::sexp::proper_list;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct GameStart {
pub game_type: GameType,
pub timeout: Timeout,
pub amount: Amount,
pub my_contribution: Amount,
pub my_turn: bool,
pub parameters: Vec<u8>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WireGameStart {
pub game_ids: Vec<GameID>,
pub start: GameStart,
}
#[derive(Debug, Clone)]
pub struct GameStartQueueEntry;
#[derive(Debug, Clone)]
pub struct MyGameStartQueueEntry {
my_games: Vec<GameStartInfo>,
their_games: Vec<GameStartInfo>,
}
/// Async interface for messaging out of the game layer toward the wallet.
///
/// For this and its companion if instances are left in the documentation which
/// refer to the potato handler combining spend bundles, that work has been decided
/// to not take place in the potato handler. The injected wallet bootstrap
/// dependency must be stateful enough that it can cope with receiving a partly
/// funded offer spend bundle and fully fund it if needed.
pub trait BootstrapTowardGame<
G: ToLocalUI + BootstrapTowardWallet + WalletSpendInterface + PacketSender,
R: Rng,
>
{
/// Gives a partly signed offer to the wallet bootstrap.
///
/// Intended use: channel_puzzle_hash delivers the desired puzzle hash and this
/// is the reply which delivers a transaction bundle for an already spent
/// transaction creating the channel coin.
///
/// The launcher program is passed a list of conditions and returns that list
/// of conditions with an announcement including their shatree as an
/// announcement.
///
/// The launcher coin is implicit in the returned transaction bundle in that
/// we can compute its coin string from this information.
///
/// The launcher coin must be a specific program such as the singleton
/// launcher.
///
/// The launcher coin targets the channel puzzle with the right amount.
///
/// "Half funded" transaction in a spend bundle to which spends will be
/// added that fully fund it, condition on the given announcement named
/// above by the launcher coin.
///
/// The launcher coin will be in here so the other guy can pick it out and
/// make the assumption that it is the launcher coin. It is identifiable by
/// its puzzle hash.
///
/// We forward this spend bundle over a potato message and the peer passes
/// it to the other guy's injected wallet dependency via received_channel_offer
/// below.
///
/// channel offer should deliver both the launcher coin id and the partly
/// funded spend bundle. Alice absolutely needs the channel coin id in some
/// way from here.
///
/// Only alice sends this spend bundle in message E, but only after receiving
/// message D.
fn channel_offer<'a>(
&mut self,
penv: &mut dyn PeerEnv<'a, G, R>,
bundle: SpendBundle,
) -> Result<(), Error>
where
R: 'a,
G: 'a;
/// Gives the fully signed offer to the wallet bootstrap.
/// Causes bob to send this spend bundle down the wire to the other peer.
///
/// When these spend bundles are combined and deduplicated, together a
/// fully spendble transaction will result, to which fee might need to be
/// added.
///
/// Alice sends this to the wallet interface via received_channel_transaction
/// completion to finish this phase of execution.
///
/// Bob receives this callback from the wallet interface with the fully funded
/// but not fee adjusted spend bundle on bob's side. It is given back to alice
/// and must contain appropriate spends to generate the launcher coin
/// announcement.
///
/// This is sent back to alice as message F.
///
/// Both alice and bob, upon knowing the full channel coin id, use the more
/// general wallet interface to register for notifications of the channel coin.
fn channel_transaction_completion<'a>(
&mut self,
penv: &mut dyn PeerEnv<'a, G, R>,
bundle: &SpendBundle,
) -> Result<(), Error>
where
R: 'a,
G: 'a;
}
/// Async interface implemented by Peer to receive notifications about wallet
/// state.
pub trait BootstrapTowardWallet {
/// Deliver the channel_puzzle_hash to the wallet.
///
/// Only alice calls this. Bob does not need this information because the
/// information needed will be held at the level of the injected object instead.
fn channel_puzzle_hash(&mut self, puzzle_hash: &PuzzleHash) -> Result<(), Error>;
/// Tells the game layer that we received a partly funded offer to which we
/// added our own coins and sent to the bootstrap wallet interface to use.
/// We had previously received a partly funded spend bundle via the reply to
/// channel_puzzle_hash,
/// Should add a fee and try to spend.
///
/// Asynchronously, channel_transaction_completion is delivered back to the
/// potato handler.
///
/// Only bob sends this, upon receiving message E, bob makes this call to
/// inform the injected wallet bootstrap dependency that the spend bundle
/// has been received (partly funded so far) and it is the job of the bootstrap
/// wallet object injected dependency to finish funding this and actually
/// spend it.
fn received_channel_offer(&mut self, bundle: &SpendBundle) -> Result<(), Error>;
/// Bob has sent this to us via the potato interface and it is given here to
/// the wallet injected dependency to actually spend. Alice must add a fee
/// if needed.
///
/// Both alice and bob, upon knowing the full channel coin id, use the more
/// general wallet interface to register for notifications of the channel coin.
fn received_channel_transaction_completion(
&mut self,
bundle: &SpendBundle,
) -> Result<(), Error>;
}
/// Spend wallet receiver
pub trait SpendWalletReceiver<
G: ToLocalUI + BootstrapTowardWallet + WalletSpendInterface + PacketSender,
R: Rng,
>
{
fn coin_created<'a>(
&mut self,
penv: &mut dyn PeerEnv<'a, G, R>,
coin_id: &CoinString,
) -> Result<(), Error>
where
G: 'a,
R: 'a;
fn coin_spent<'a>(
&mut self,
penv: &mut dyn PeerEnv<'a, G, R>,
coin_id: &CoinString,
) -> Result<(), Error>
where
G: 'a,
R: 'a;
fn coin_timeout_reached<'a>(
&mut self,
penv: &mut dyn PeerEnv<'a, G, R>,
coin_id: &CoinString,
) -> Result<(), Error>
where
G: 'a,
R: 'a;
}
/// Unroll time wallet interface.
pub trait WalletSpendInterface {
/// Enqueue an outbound transaction.
fn spend_transaction_and_add_fee(&mut self, bundle: &Spend) -> Result<(), Error>;
/// Coin should report its lifecycle until it gets spent, then should be
/// de-registered.
fn register_coin(&mut self, coin_id: &CoinString, timeout: &Timeout) -> Result<(), Error>;
}
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq, PartialOrd, Ord)]
pub struct GameType(pub Vec<u8>);
pub trait ToLocalUI {
fn opponent_moved(&mut self, id: &GameID, readable: ReadableMove) -> Result<(), Error>;
fn game_message(&mut self, id: &GameID, readable: &[u8]) -> Result<(), Error>;
fn game_finished(&mut self, id: &GameID, my_share: Amount) -> Result<(), Error>;
fn game_cancelled(&mut self, id: &GameID) -> Result<(), Error>;
fn shutdown_complete(&mut self, reward_coin_string: &CoinString) -> Result<(), Error>;
fn going_on_chain(&mut self) -> Result<(), Error>;
}
pub trait FromLocalUI<
G: ToLocalUI + BootstrapTowardWallet + WalletSpendInterface + PacketSender,
R: Rng,
>
{
/// Start games requires queueing so that we handle them one at a time only
/// when the previous start game.
///
/// Queue of games we want to start that are also waiting after this.
///
/// We must request the potato if not had.
///
/// General flow:
///
/// Have queues of games we're starting and other side is starting.
fn start_games<'a>(
&mut self,
penv: &mut dyn PeerEnv<'a, G, R>,
i_initiated: bool,
game: &GameStart,
) -> Result<Vec<GameID>, Error>
where
G: 'a,
R: 'a;
fn make_move<'a>(
&mut self,
penv: &mut dyn PeerEnv<'a, G, R>,
id: &GameID,
readable: &ReadableMove,
) -> Result<(), Error>
where
G: 'a,
R: 'a;
fn accept<'a>(&mut self, penv: &mut dyn PeerEnv<'a, G, R>, id: &GameID) -> Result<(), Error>
where
G: 'a,
R: 'a;
fn shut_down(&mut self) -> Result<(), Error>;
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct HandshakeB {
channel_public_key: PublicKey,
unroll_public_key: PublicKey,
reward_puzzle_hash: PuzzleHash,
referee_puzzle_hash: PuzzleHash,
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct HandshakeA {
parent: CoinString,
simple: HandshakeB,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum PeerMessage {
// Fixed in order sequence
HandshakeA(HandshakeA),
HandshakeB(HandshakeB),
/// Includes spend of launcher coin id.
HandshakeE {
bundle: SpendBundle,
},
HandshakeF {
bundle: SpendBundle,
},
Nil(PotatoSignatures),
Move(GameID, MoveResult),
Accept(GameID, Amount, PotatoSignatures),
Shutdown(Aggsig),
RequestPotato(()),
StartGames(PotatoSignatures, Vec<FlatGameStartInfo>),
}
#[derive(Debug, Clone)]
pub struct HandshakeStepInfo {
#[allow(dead_code)]
pub first_player_hs_info: HandshakeA,
#[allow(dead_code)]
pub second_player_hs_info: HandshakeB,
}
#[derive(Debug, Clone)]
pub struct HandshakeStepWithSpend {
#[allow(dead_code)]
pub info: HandshakeStepInfo,
#[allow(dead_code)]
pub spend: SpendBundle,
}
#[derive(Debug)]
pub enum HandshakeState {
StepA,
StepB,
StepC(CoinString, Box<HandshakeA>),
StepD(Box<HandshakeStepInfo>),
StepE(Box<HandshakeStepInfo>),
PostStepE(Box<HandshakeStepInfo>),
StepF(Box<HandshakeStepInfo>),
PostStepF(Box<HandshakeStepInfo>),
Finished(Box<HandshakeStepWithSpend>),
}
pub trait PacketSender {
fn send_message(&mut self, msg: &PeerMessage) -> Result<(), Error>;
}
pub trait PeerEnv<'inputs, G, R>
where
G: ToLocalUI + WalletSpendInterface + BootstrapTowardWallet + PacketSender,
R: Rng,
{
fn env(&mut self) -> (&mut ChannelHandlerEnv<'inputs, R>, &mut G);
}
enum PotatoState {
Absent,
Requested,
Present,
}
enum GameAction {
Move(GameID, ReadableMove),
Accept(GameID),
}
/// Handle potato in flight when I request potato:
///
/// Every time i send the potato, if i have stuff i want to do, then i also send
/// the request potato message directly after so I can be prompted to take another
/// thing off.
///
/// General workflow:
///
/// Whenever we receive the potato, check the work queues, notify channel handler,
/// then take the channel handler result with the potato and send it on.
///
/// If there is more work left, also send a receive potato message at that time.
///
/// Also do this when any queue becomes non-empty.
///
/// State machine surrounding game starts:
///
/// First peer receives game start from the ui
/// First peer tries to acquire the potato and when we have it, send a peer level start game
/// message.
/// First peer creates the game by giving channel_handler the game definitions.
/// second peer receives the game start from the first peer and stores it.
///
/// When the channel handler game start is reeived, we must receive a matching datum to
/// the one we receive in the channel handler game start. If we receive that, we allow
/// the message through to the channel handler.
#[allow(dead_code)]
pub struct PotatoHandler {
initiator: bool,
have_potato: PotatoState,
handshake_state: HandshakeState,
// Waiting game starts at the peer level.
their_start_queue: VecDeque<GameStartQueueEntry>,
// Our outgoing game starts.
my_start_queue: VecDeque<MyGameStartQueueEntry>,
game_action_queue: VecDeque<GameAction>,
next_game_id: Vec<u8>,
channel_handler: Option<ChannelHandler>,
channel_initiation_transaction: Option<SpendBundle>,
channel_finished_transaction: Option<SpendBundle>,
game_types: BTreeMap<GameType, Program>,
private_keys: ChannelHandlerPrivateKeys,
my_contribution: Amount,
their_contribution: Amount,
reward_puzzle_hash: PuzzleHash,
waiting_to_start: bool,
channel_timeout: Timeout,
}
fn init_game_id(private_keys: &ChannelHandlerPrivateKeys) -> Vec<u8> {
Sha256Input::Array(vec![
Sha256Input::Bytes(&private_keys.my_channel_coin_private_key.bytes()),
Sha256Input::Bytes(&private_keys.my_unroll_coin_private_key.bytes()),
Sha256Input::Bytes(&private_keys.my_referee_private_key.bytes()),
])
.hash()
.bytes()
.to_vec()
}
/// Peer interface for high level opaque messages.
///
/// ch1 has generated public key and passed that info via handshake a message to
/// peer 2 into ch2.
/// When alice gets message b, she sends a nil potato.
/// and at the same time calls up the stack, telling the owner "here is the initial
/// channel public key".
///
/// bob is going to do the same thing when he gets message b.
///
/// Alice is just going to get a message back from her peer after giving the
/// channel public key (finished aggregating).
///
/// Alice forgets the channel offer after sending it to bob (received via received_channel_offer from the wallet bootstrap object).
/// Bob receivs channel offer then is given the transaction completion by watching
/// the blockchain.
///
/// Alice sends the "received channel transaction completion" message.
///
/// once this object knows the channel puzzle hash they should register the coin.
impl PotatoHandler {
pub fn new(
have_potato: bool,
private_keys: ChannelHandlerPrivateKeys,
game_types: BTreeMap<GameType, Program>,
my_contribution: Amount,
their_contribution: Amount,
channel_timeout: Timeout,
reward_puzzle_hash: PuzzleHash,
) -> PotatoHandler {
PotatoHandler {
initiator: have_potato,
have_potato: if have_potato {
PotatoState::Present
} else {
PotatoState::Absent
},
handshake_state: if have_potato {
HandshakeState::StepA
} else {
HandshakeState::StepB
},
next_game_id: Vec::new(),
game_types,
their_start_queue: VecDeque::default(),
my_start_queue: VecDeque::default(),
game_action_queue: VecDeque::default(),
channel_handler: None,
channel_initiation_transaction: None,
channel_finished_transaction: None,
waiting_to_start: true,
private_keys,
my_contribution,
their_contribution,
channel_timeout,
reward_puzzle_hash,
}
}
pub fn is_initiator(&self) -> bool {
self.initiator
}
pub fn channel_handler(&self) -> Result<&ChannelHandler, Error> {
if let Some(ch) = &self.channel_handler {
Ok(ch)
} else {
Err(Error::StrErr("no channel handler".to_string()))
}
}
fn channel_handler_mut(&mut self) -> Result<&mut ChannelHandler, Error> {
if let Some(ch) = &mut self.channel_handler {
Ok(ch)
} else {
Err(Error::StrErr("no channel handler".to_string()))
}
}
pub fn handshake_finished(&self) -> bool {
matches!(self.handshake_state, HandshakeState::Finished(_))
}
/// Tell whether this peer has the potato. If it has been sent but not received yet
/// then both will say false
pub fn has_potato(&self) -> bool {
matches!(self.have_potato, PotatoState::Present)
}
pub fn start<'a, G, R: Rng + 'a>(
&mut self,
penv: &'a mut dyn PeerEnv<'a, G, R>,
parent_coin: CoinString,
) -> Result<(), Error>
where
G: ToLocalUI + BootstrapTowardWallet + WalletSpendInterface + PacketSender,
{
let (env, system_interface) = penv.env();
let channel_public_key =
private_to_public_key(&self.private_keys.my_channel_coin_private_key);
let unroll_public_key =
private_to_public_key(&self.private_keys.my_unroll_coin_private_key);
let referee_public_key = private_to_public_key(&self.private_keys.my_referee_private_key);
let referee_puzzle_hash = puzzle_hash_for_pk(env.allocator, &referee_public_key)?;
debug!("Start: our channel public key {:?}", channel_public_key);
assert!(matches!(self.handshake_state, HandshakeState::StepA));
let my_hs_info = HandshakeA {
parent: parent_coin.clone(),
simple: HandshakeB {
channel_public_key,
unroll_public_key,
reward_puzzle_hash: self.reward_puzzle_hash.clone(),
referee_puzzle_hash,
},
};
self.handshake_state =
HandshakeState::StepC(parent_coin.clone(), Box::new(my_hs_info.clone()));
system_interface.send_message(&PeerMessage::HandshakeA(my_hs_info))?;
Ok(())
}
fn update_channel_coin_after_receive<'a, G, R: Rng + 'a>(
&mut self,
penv: &mut dyn PeerEnv<'a, G, R>,
_spend: &ChannelCoinSpendInfo,
) -> Result<(), Error>
where
G: ToLocalUI + BootstrapTowardWallet + WalletSpendInterface + PacketSender + 'a,
{
self.have_potato = PotatoState::Present;
if self.have_potato_start_game(penv)? {
return Ok(());
}
if self.have_potato_move(penv)? {
return Ok(());
}
Ok(())
}
fn pass_on_channel_handler_message<'a, G, R: Rng + 'a>(
&mut self,
penv: &mut dyn PeerEnv<'a, G, R>,
msg: Vec<u8>,
) -> Result<(), Error>
where
G: ToLocalUI + BootstrapTowardWallet + WalletSpendInterface + PacketSender + 'a,
{
let ch = self.channel_handler_mut()?;
let doc = bson::Document::from_reader(&mut msg.as_slice()).into_gen()?;
let msg_envelope: PeerMessage = bson::from_bson(bson::Bson::Document(doc)).into_gen()?;
debug!("msg {msg_envelope:?}");
match msg_envelope {
PeerMessage::Nil(n) => {
debug!("about to receive empty potato");
let spend_info = {
let (env, _system_interface) = penv.env();
ch.received_empty_potato(env, &n)?
};
self.update_channel_coin_after_receive(penv, &spend_info)?;
}
PeerMessage::Move(game_id, m) => {
let (spend_info, readable_move, message) = {
let (env, _) = penv.env();
ch.received_potato_move(env, &game_id, &m)?
};
{
let (_, system_interface) = penv.env();
system_interface
.opponent_moved(&game_id, ReadableMove::from_nodeptr(readable_move))?;
if !message.is_empty() {
system_interface.game_message(&game_id, &message)?;
}
}
self.update_channel_coin_after_receive(penv, &spend_info)?;
}
PeerMessage::Accept(game_id, amount, sigs) => {
let spend_info = {
let (env, system_interface) = penv.env();
let result = ch.received_potato_accept(env, &sigs, &game_id)?;
system_interface.game_finished(&game_id, amount)?;
Ok(result)
}?;
self.update_channel_coin_after_receive(penv, &spend_info)?;
}
_ => {
todo!("unhandled passthrough message {msg_envelope:?}");
}
}
Ok(())
}
pub fn try_complete_step_e<'a, G, R: Rng + 'a>(
&mut self,
penv: &mut dyn PeerEnv<'a, G, R>,
first_player_hs_info: HandshakeA,
second_player_hs_info: HandshakeB,
) -> Result<(), Error>
where
G: ToLocalUI + BootstrapTowardWallet + WalletSpendInterface + PacketSender + 'a,
{
if let Some(spend) = self.channel_initiation_transaction.as_ref() {
self.handshake_state = HandshakeState::Finished(Box::new(HandshakeStepWithSpend {
info: HandshakeStepInfo {
first_player_hs_info,
second_player_hs_info,
},
spend: spend.clone(),
}));
// Outer layer already knows the launcher coin string.
//
// Provide the channel puzzle hash to the full node bootstrap and
// it replies with the channel puzzle hash
{
let (_env, system_interface) = penv.env();
system_interface.send_message(&PeerMessage::HandshakeE {
bundle: spend.clone(),
})?;
}
}
Ok(())
}
pub fn try_complete_step_f<'a, G, R: Rng + 'a>(
&mut self,
penv: &mut dyn PeerEnv<'a, G, R>,
first_player_hs_info: HandshakeA,
second_player_hs_info: HandshakeB,
) -> Result<(), Error>
where
G: ToLocalUI + BootstrapTowardWallet + WalletSpendInterface + PacketSender + 'a,
{
// Haven't got the channel coin yet.
if self.waiting_to_start {
debug!("waiting to start");
return Ok(());
}
if let Some(spend) = self.channel_finished_transaction.as_ref() {
self.handshake_state = HandshakeState::Finished(Box::new(HandshakeStepWithSpend {
info: HandshakeStepInfo {
first_player_hs_info,
second_player_hs_info,
},
spend: spend.clone(),
}));
// Outer layer already knows the launcher coin string.
//
// Provide the channel puzzle hash to the full node bootstrap and
// it replies with the channel puzzle hash
{
let (_env, system_interface) = penv.env();
system_interface.send_message(&PeerMessage::HandshakeF {
bundle: spend.clone(),
})?;
}
}
Ok(())
}
// We have the potato so we can send a message that starts a game if there are games
// to start.
//
// This returns bool so that it can be put into the receive potato pipeline so we
// can automatically send new game starts on the next potato receive.
fn have_potato_start_game<'a, G, R: Rng + 'a>(
&mut self,
penv: &mut dyn PeerEnv<'a, G, R>,
) -> Result<bool, Error>
where
G: ToLocalUI + BootstrapTowardWallet + WalletSpendInterface + PacketSender + 'a,
{
if let Some(desc) = self.my_start_queue.pop_front() {
let mut dehydrated_games = Vec::new();
let sigs = {
let ch = self.channel_handler_mut()?;
let (env, _) = penv.env();
for game in desc.their_games.iter() {
dehydrated_games.push(game.to_serializable(env.allocator)?);
}
for game in desc.my_games.iter() {
debug!(
"using game {:?}",
PrintableGameStartInfo {
allocator: env.allocator.allocator(),
info: game
}
);
}
ch.send_potato_start_game(env, &desc.my_games)?
};
debug!("dehydrated_games {dehydrated_games:?}");
let (_, system_interface) = penv.env();
system_interface.send_message(&PeerMessage::StartGames(sigs, dehydrated_games))?;
return Ok(true);
}
Ok(false)
}
fn have_potato_move<'a, G, R: Rng + 'a>(
&mut self,
penv: &mut dyn PeerEnv<'a, G, R>,
) -> Result<bool, Error>
where
G: ToLocalUI + BootstrapTowardWallet + WalletSpendInterface + PacketSender + 'a,
{
match self.game_action_queue.pop_front() {
Some(GameAction::Move(game_id, readable_move)) => {
let move_result = {
let ch = self.channel_handler_mut()?;
let (env, _) = penv.env();
ch.send_potato_move(env, &game_id, &readable_move)?
};
let (_, system_interface) = penv.env();
system_interface.send_message(&PeerMessage::Move(game_id, move_result))?;
self.have_potato = PotatoState::Absent;
Ok(true)
}
Some(GameAction::Accept(game_id)) => {
let (sigs, amount) = {
let ch = self.channel_handler_mut()?;
let (env, _) = penv.env();
ch.send_potato_accept(env, &game_id)?
};
let (_, system_interface) = penv.env();
system_interface.send_message(&PeerMessage::Accept(
game_id.clone(),
amount.clone(),
sigs,
))?;
system_interface.game_finished(&game_id, amount)?;
self.have_potato = PotatoState::Absent;
Ok(true)
}
None => Ok(false),
}
}
fn get_games_by_start_type<'a, G, R: Rng + 'a>(
&mut self,
penv: &mut dyn PeerEnv<'a, G, R>,
game_start: &GameStart,
) -> Result<(Vec<GameStartInfo>, Vec<GameStartInfo>), Error>
where
G: ToLocalUI + BootstrapTowardWallet + WalletSpendInterface + PacketSender + 'a,
{
let starter = if let Some(starter) = self.game_types.get(&game_start.game_type) {
starter
} else {
return Err(Error::StrErr(format!(
"no such game {:?}",
game_start.game_type
)));
};
let (env, _) = penv.env();
let starter_clvm = starter.to_clvm(env.allocator).into_gen()?;
let params_clvm =
node_from_bytes(env.allocator.allocator(), &game_start.parameters).into_gen()?;
let program_run_args = (
game_start.amount.clone(),
(game_start.my_contribution.clone(), (Node(params_clvm), ())),
)
.to_clvm(env.allocator)
.into_gen()?;
let program_output = run_program(
env.allocator.allocator(),
&chia_dialect(),
starter_clvm,
program_run_args,
0,
)
.into_gen()?
.1;
let to_list =
|allocator: &mut Allocator, node: NodePtr, err: &str| -> Result<Vec<NodePtr>, Error> {
if let Some(p) = proper_list(allocator, node, true) {
Ok(p)
} else {
Err(Error::StrErr(format!("bad factory output: {err}")))
}
};
// The result is two parallel lists of opposite sides of game starts.
// Well re-glue these together into a list of pairs.
let pair_of_output_lists = to_list(
env.allocator.allocator(),
program_output,
"not a pair of lists",
)?;
if pair_of_output_lists.len() != 2 {
return Err(Error::StrErr("output wasn't a list of 2 items".to_string()));
}
let my_info_list = to_list(
env.allocator.allocator(),
pair_of_output_lists[0],
"not a list (first)",
)?;
let their_info_list = to_list(
env.allocator.allocator(),
pair_of_output_lists[1],
"not a list (second)",
)?;
if their_info_list.len() != my_info_list.len() {
return Err(Error::StrErr(
"mismatched my and their game starts".to_string(),
));
}
let mut game_ids = Vec::new();
for _ in my_info_list.iter() {
game_ids.push(self.next_game_id()?);
}
let convert_info_list = |allocator: &mut AllocEncoder,
my_turn: bool,
my_info_list: &[NodePtr]|
-> Result<Vec<GameStartInfo>, Error> {
let mut result_start_info = Vec::new();
for (i, node) in my_info_list.iter().enumerate() {
let new_game = GameStartInfo::from_clvm(allocator, my_turn, *node)?;
// Timeout and game_id are supplied here.
result_start_info.push(GameStartInfo {
game_id: game_ids[i].clone(),
timeout: game_start.timeout.clone(),
..new_game
});
}
Ok(result_start_info)
};
let my_result_start_info = convert_info_list(env.allocator, true, &my_info_list)?;
let their_result_start_info = convert_info_list(env.allocator, false, &their_info_list)?;
Ok((my_result_start_info, their_result_start_info))
}
fn request_potato<'a, G, R: Rng + 'a>(
&mut self,
penv: &mut dyn PeerEnv<'a, G, R>,
) -> Result<(), Error>
where
G: ToLocalUI + BootstrapTowardWallet + WalletSpendInterface + PacketSender + 'a,
{
if matches!(self.have_potato, PotatoState::Requested) {
return Ok(());
}
debug!("requesting potato");
let (_, system_interface) = penv.env();
system_interface.send_message(&PeerMessage::RequestPotato(()))?;
self.have_potato = PotatoState::Requested;
Ok(())
}
fn next_game_id(&mut self) -> Result<GameID, Error> {
if self.next_game_id.is_empty() {
return Err(Error::StrErr("no game id set".to_string()));
}
let game_id = self.next_game_id.clone();
for b in self.next_game_id.iter_mut() {
*b += 1;
if *b != 0 {
break;
}
}
Ok(GameID::from_bytes(&game_id))
}
fn received_game_start<'a, G, R: Rng + 'a>(
&mut self,
penv: &mut dyn PeerEnv<'a, G, R>,
sigs: &PotatoSignatures,
games: &[FlatGameStartInfo],
) -> Result<(), Error>
where
G: ToLocalUI + BootstrapTowardWallet + WalletSpendInterface + PacketSender + 'a,
{
// We must have received a peer layer message indicating that we're waiting for this
// game start.
if self.their_start_queue.pop_front().is_none() {
return Err(Error::StrErr("no waiting games to start".to_string()));
};
let ch = self.channel_handler_mut()?;
let spend_info = {
let (env, _system_interface) = penv.env();
let mut rehydrated_games = Vec::new();
for game in games.iter() {
let new_rehydrated_game = GameStartInfo::from_serializable(env.allocator, game)?;
let re_dehydrated = new_rehydrated_game.to_serializable(env.allocator)?;
assert_eq!(&re_dehydrated, game);
debug!(
"their game {:?}",
PrintableGameStartInfo {
allocator: env.allocator.allocator(),
info: &new_rehydrated_game
}
);
rehydrated_games.push(new_rehydrated_game);
}
ch.received_potato_start_game(env, sigs, &rehydrated_games)?
};
self.update_channel_coin_after_receive(penv, &spend_info)?;
Ok(())
}
pub fn received_message<'a, G, R: Rng + 'a>(
&mut self,
penv: &mut dyn PeerEnv<'a, G, R>,
msg: Vec<u8>,
) -> Result<(), Error>
where
G: ToLocalUI + BootstrapTowardWallet + WalletSpendInterface + PacketSender + 'a,
{
let doc = bson::Document::from_reader(&mut msg.as_slice()).into_gen()?;
let make_channel_handler_initiation =
|parent: CoinID, start_potato, msg: &HandshakeB| ChannelHandlerInitiationData {
launcher_coin_id: parent,
we_start_with_potato: start_potato,
their_channel_pubkey: msg.channel_public_key.clone(),
their_unroll_pubkey: msg.unroll_public_key.clone(),
their_referee_puzzle_hash: msg.referee_puzzle_hash.clone(),
my_contribution: self.my_contribution.clone(),
their_contribution: self.their_contribution.clone(),
};
match &self.handshake_state {
// non potato progression
HandshakeState::StepA => {
let msg_envelope: PeerMessage =
bson::from_bson(bson::Bson::Document(doc)).into_gen()?;
let msg = if let PeerMessage::HandshakeA(msg) = msg_envelope {
msg
} else {
return Err(Error::StrErr(format!(