-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcolcript.py
More file actions
executable file
·1838 lines (1492 loc) · 68.4 KB
/
Copy pathcolcript.py
File metadata and controls
executable file
·1838 lines (1492 loc) · 68.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
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
#!/usr/bin/env python3
# colcript.py - Interfaz principal de ColCript
import os
import sys
# Obtener ruta absoluta del proyecto
project_root = os.path.dirname(os.path.abspath(__file__))
if project_root not in sys.path:
sys.path.insert(0, project_root)
from blockchain.blockchain import Blockchain
from wallet.wallet import Wallet
from blockchain.storage import BlockchainStorage
from wallet.transaction_history import TransactionHistory
from blockchain.block_explorer import BlockExplorer
from utils.statistics import BlockchainStatistics
from utils.charts import create_bar_chart, create_progress_bar, create_percentage_bar, print_table
from wallet.faucet import Faucet
from contracts.smart_contract import ContractManager, ContractType
from network.node import Node
import config
class ColCriptCLI:
def __init__(self):
self.blockchain = None
self.wallet = None
self.running = True
self.contract_manager = None
self.p2p_node = None
self.storage = BlockchainStorage()
def show_banner(self):
"""Muestra el banner de ColCript"""
print("\n" + "="*60)
print(f"{'🪙 ' + config.COIN_NAME + ' (' + config.COIN_SYMBOL + ')':^60}")
print(f"{'Criptomoneda Blockchain v' + config.VERSION:^60}")
print("="*60 + "\n")
def show_menu(self):
"""Muestra el menú principal"""
print("\n📋 MENÚ PRINCIPAL:")
print(" 1. Crear nueva blockchain")
print(" 2. Cargar blockchain existente")
print(" 3. Listar blockchains guardadas")
print(" 4. Crear nueva wallet")
print(" 5. Cargar wallet existente")
print(" 6. Ver balance")
print(" 7. Ver historial de transacciones")
print(" 8. Explorador de bloques")
print(" 9. Estadísticas y métricas")
print(" 10. Faucet (CLC gratis)")
print(" 11. Enviar ColCript")
print(" 12. Minar bloque")
print(" 13. Ver blockchain")
print(" 14. Ver información")
print(" 15. Guardar wallet")
print(" 16. Guardar blockchain manualmente")
print(" 17. Ajuste de dificultad")
print(" 18. Smart Contract")
print(" 19. Red P2P")
print(" 0. Salir")
print()
def create_blockchain(self):
"""Crea una nueva blockchain"""
print("\n⛓️ Creando nueva blockchain...")
# Preguntar si desea auto-guardado
auto_save_input = input("¿Activar auto-guardado? (S/n): ").strip().lower()
auto_save = auto_save_input != 'n'
if auto_save:
filename = input("Nombre del archivo (Enter para 'colcript_main.json'): ").strip()
if not filename:
filename = "colcript_main.json"
self.blockchain = Blockchain(auto_save=True, save_filename=filename)
else:
self.blockchain = Blockchain(auto_save=False)
print("✅ Blockchain creada exitosamente\n")
def load_blockchain(self):
"""Carga una blockchain existente"""
blockchains = self.storage.list_blockchains()
if not blockchains:
return
choice = input("\nNúmero de blockchain a cargar (0 para cancelar): ").strip()
try:
choice_num = int(choice)
if choice_num == 0:
print("Cancelado\n")
return
if 1 <= choice_num <= len(blockchains):
filename = blockchains[choice_num - 1]['filename']
print(f"\n📂 Cargando {filename}...")
loaded_bc = self.storage.load_blockchain(filename)
if loaded_bc:
# Configurar auto-guardado
loaded_bc.storage = self.storage
loaded_bc.save_filename = filename
loaded_bc.auto_save = True
self.blockchain = loaded_bc
print(f"✅ Blockchain cargada con {len(self.blockchain.chain)} bloques\n")
else:
print("❌ Error al cargar blockchain\n")
else:
print("❌ Opción inválida\n")
except ValueError:
print("❌ Entrada inválida\n")
def list_saved_blockchains(self):
"""Lista todas las blockchains guardadas"""
self.storage.list_blockchains()
input("\nPresiona Enter para continuar...")
def create_wallet(self):
"""Crea una nueva wallet"""
name = input("\n💼 Nombre de la wallet: ").strip()
if not name:
name = "My Wallet"
self.wallet = Wallet(name)
print()
def load_wallet(self):
"""Carga una wallet desde archivo"""
filename = input("\n📂 Nombre del archivo (ej: Mi_Wallet.json): ").strip()
if not filename.endswith('.json'):
filename += '.json'
self.wallet = Wallet.load_from_file(filename)
print()
def view_balance(self):
"""Muestra el balance de la wallet"""
if not self.wallet:
print("\n❌ Primero debes crear o cargar una wallet\n")
return
if not self.blockchain:
print("\n❌ Primero debes crear una blockchain\n")
return
balance = self.wallet.get_balance(self.blockchain)
print(f"\n💰 Balance de '{self.wallet.name}':")
print(f" {balance} {config.COIN_SYMBOL}")
print(f" Dirección: {self.wallet.get_address()[:40]}...\n")
def view_transaction_history(self):
"""Muestra el menú de historial de transacciones"""
if not self.wallet:
print("\n❌ Primero debes crear o cargar una wallet\n")
return
if not self.blockchain:
print("\n❌ Primero debes crear una blockchain\n")
return
# Crear analizador de historial
history = TransactionHistory(self.blockchain, self.wallet.get_address())
while True:
print("\n📜 MENÚ DE HISTORIAL")
print(" 1. Ver resumen")
print(" 2. Ver todas las transacciones")
print(" 3. Ver solo transacciones enviadas")
print(" 4. Ver solo transacciones recibidas")
print(" 5. Ver solo recompensas de minado")
print(" 6. Exportar historial a JSON")
print(" 0. Volver al menú principal")
print()
choice = input("Selecciona una opción: ").strip()
if choice == '1':
history.print_summary()
input("\nPresiona Enter para continuar...")
elif choice == '2':
history.print_all_transactions()
input("\nPresiona Enter para continuar...")
elif choice == '3':
sent = history.get_sent_transactions()
if not sent:
print("\n📭 No hay transacciones enviadas\n")
else:
print(f"\n📤 TRANSACCIONES ENVIADAS ({len(sent)})")
for i, tx in enumerate(sent, 1):
history.print_transaction(tx, i)
input("\nPresiona Enter para continuar...")
elif choice == '4':
received = history.get_received_transactions()
if not received:
print("\n📭 No hay transacciones recibidas\n")
else:
print(f"\n📥 TRANSACCIONES RECIBIDAS ({len(received)})")
for i, tx in enumerate(received, 1):
history.print_transaction(tx, i)
input("\nPresiona Enter para continuar...")
elif choice == '5':
mining = history.get_mining_rewards()
if not mining:
print("\n📭 No hay recompensas de minado\n")
else:
print(f"\n⛏️ RECOMPENSAS DE MINADO ({len(mining)})")
for i, tx in enumerate(mining, 1):
history.print_transaction(tx, i)
input("\nPresiona Enter para continuar...")
elif choice == '6':
filename = input("\nNombre del archivo (Enter para automático): ").strip()
if filename:
history.export_to_json(filename)
else:
history.export_to_json()
input("Presiona Enter para continuar...")
elif choice == '0':
break
else:
print("\n❌ Opción inválida\n")
def block_explorer_menu(self):
"""Muestra el menú del explorador de bloques"""
if not self.blockchain:
print("\n❌ Primero debes crear o cargar una blockchain\n")
return
explorer = BlockExplorer(self.blockchain)
while True:
print("\n🔍 EXPLORADOR DE BLOQUES")
print(" 1. Ver estadísticas de la blockchain")
print(" 2. Ver bloque por número")
print(" 3. Buscar bloque por hash")
print(" 4. Buscar bloques por minero")
print(" 5. Ver último bloque")
print(" 6. Navegar por bloques")
print(" 7. Verificar bloque específico")
print(" 8. Exportar bloque a JSON")
print(" 0. Volver al menú principal")
print()
choice = input("Selecciona una opción: ").strip()
if choice == '1':
explorer.print_blockchain_stats()
input("\nPresiona Enter para continuar...")
elif choice == '2':
try:
num = int(input("\nNúmero de bloque: ").strip())
block = explorer.get_block_by_number(num)
if block:
explorer.print_block_detailed(block)
else:
print(f"\n❌ Bloque #{num} no existe\n")
except ValueError:
print("\n❌ Número inválido\n")
input("\nPresiona Enter para continuar...")
elif choice == '3':
hash_input = input("\nHash del bloque (completo o parcial): ").strip()
if hash_input:
block = explorer.get_block_by_hash(hash_input)
if block:
explorer.print_block_detailed(block)
else:
print(f"\n❌ No se encontró bloque con ese hash\n")
else:
print("\n❌ Hash inválido\n")
input("\nPresiona Enter para continuar...")
elif choice == '4':
address = input("\nDirección del minero (completa o parcial): ").strip()
if address:
blocks = explorer.search_blocks_by_miner(address)
if blocks:
print(f"\n⛏️ BLOQUES MINADOS POR {address[:40]}...")
print(f" Total encontrados: {len(blocks)}\n")
for block in blocks:
explorer.print_block_summary(block)
else:
print(f"\n❌ No se encontraron bloques minados por esa dirección\n")
else:
print("\n❌ Dirección inválida\n")
input("\nPresiona Enter para continuar...")
elif choice == '5':
last_block = self.blockchain.get_latest_block()
print("\n🆕 ÚLTIMO BLOQUE:")
explorer.print_block_detailed(last_block)
input("\nPresiona Enter para continuar...")
elif choice == '6':
self._navigate_blocks(explorer)
elif choice == '7':
try:
num = int(input("\nNúmero de bloque a verificar: ").strip())
block = explorer.get_block_by_number(num)
if block:
verification = explorer.verify_block(block)
print(f"\n🔍 VERIFICACIÓN DEL BLOQUE #{num}")
print("="*60)
if verification['valid']:
print("✅ El bloque es válido")
else:
print("❌ El bloque tiene problemas:")
for issue in verification['issues']:
print(f" • {issue}")
print("="*60 + "\n")
else:
print(f"\n❌ Bloque #{num} no existe\n")
except ValueError:
print("\n❌ Número inválido\n")
input("\nPresiona Enter para continuar...")
elif choice == '8':
try:
num = int(input("\nNúmero de bloque a exportar: ").strip())
block = explorer.get_block_by_number(num)
if block:
filename = input("Nombre del archivo (Enter para automático): ").strip()
if filename:
explorer.export_block(block, filename)
else:
explorer.export_block(block)
else:
print(f"\n❌ Bloque #{num} no existe\n")
except ValueError:
print("\n❌ Número inválido\n")
input("\nPresiona Enter para continuar...")
elif choice == '0':
break
else:
print("\n❌ Opción inválida\n")
def statistics_menu(self):
"""Muestra el menú de estadísticas y métricas"""
if not self.blockchain:
print("\n❌ Primero debes crear o cargar una blockchain\n")
return
stats = BlockchainStatistics(self.blockchain)
while True:
print("\n📊 ESTADÍSTICAS Y MÉTRICAS")
print(" 1. Dashboard completo")
print(" 2. Supply y circulación")
print(" 3. Top wallets")
print(" 4. Distribución de riqueza")
print(" 5. Estadísticas de minería")
print(" 6. Estadísticas de transacciones")
print(" 7. Salud de la red")
print(" 0. Volver al menú principal")
print()
choice = input("Selecciona una opción: ").strip()
if choice == '1':
self._show_complete_dashboard(stats)
elif choice == '2':
self._show_supply_stats(stats)
elif choice == '3':
self._show_top_wallets(stats)
elif choice == '4':
self._show_wealth_distribution(stats)
elif choice == '5':
self._show_mining_stats(stats)
elif choice == '6':
self._show_transaction_stats(stats)
elif choice == '7':
self._show_network_health(stats)
elif choice == '0':
break
else:
print("\n❌ Opción inválida\n")
def difficulty_menu(self):
"""Muestra el menú de ajuste de dificultad"""
if not self.blockchain:
print("\n❌ Primero debes crear o cargar una blockchain\n")
return
from blockchain.difficulty import DifficultyAdjustment
while True:
print("\n⚙️ AJUSTE DE DIFICULTAD")
print(" 1. Ver información de dificultad")
print(" 2. Configurar dificultad manual")
print(" 3. Habilitar/deshabilitar ajuste automático")
print(" 4. Configurar tiempo objetivo")
print(" 5. Configurar intervalo de ajuste")
print(" 0. Volver al menú principal")
print()
choice = input("Selecciona una opción: ").strip()
if choice == '1':
self._show_difficulty_info()
elif choice == '2':
self._set_manual_difficulty()
elif choice == '3':
self._toggle_auto_adjustment()
elif choice == '4':
self._set_target_block_time()
elif choice == '5':
self._set_adjustment_interval()
elif choice == '0':
break
else:
print("\n❌ Opción inválida\n")
def contracts_menu(self):
"""Muestra el menú de smart contracts"""
if not self.blockchain:
print("\n❌ Primero debes crear o cargar una blockchain\n")
return
# Inicializar contract manager si no existe
if self.contract_manager is None:
self.contract_manager = ContractManager(self.blockchain)
while True:
print("\n📜 SMART CONTRACTS")
print(" 1. Crear Timelock")
print(" 2. Crear Multisig")
print(" 3. Crear Escrow")
print(" 4. Listar contratos")
print(" 5. Ver contrato")
print(" 6. Ejecutar contrato")
print(" 7. Firmar contrato (Multisig)")
print(" 8. Decidir Escrow")
print(" 0. Volver al menú principal")
print()
choice = input("Selecciona una opción: ").strip()
if choice == '1':
self._create_timelock()
elif choice == '2':
self._create_multisig()
elif choice == '3':
self._create_escrow()
elif choice == '4':
self._list_contracts()
elif choice == '5':
self._view_contract()
elif choice == '6':
self._execute_contract()
elif choice == '7':
self._sign_multisig()
elif choice == '8':
self._decide_escrow()
elif choice == '0':
break
else:
print("\n❌ Opción inválida\n")
def network_menu(self):
"""Muestra el menú de red P2P"""
if not self.blockchain:
print("\n❌ Primero debes crear o cargar una blockchain\n")
return
# Inicializar nodo P2P si no existe
if self.p2p_node is None:
print("\n🌐 Iniciando nodo P2P...")
self.p2p_node = Node(host='127.0.0.1', port=6000, blockchain=self.blockchain)
self.p2p_node.start()
while True:
print("\n🌐 RED P2P")
print(" 1. Información del nodo")
print(" 2. Listar peers")
print(" 3. Agregar peer")
print(" 4. Eliminar peer")
print(" 5. Sincronizar con red")
print(" 6. Descubrir peers")
print(" 7. Detener nodo")
print(" 0. Volver al menú principal")
print()
choice = input("Selecciona una opción: ").strip()
if choice == '1':
self._show_node_info()
elif choice == '2':
self._list_peers()
elif choice == '3':
self._add_peer()
elif choice == '4':
self._remove_peer()
elif choice == '5':
self._sync_network()
elif choice == '6':
self._discover_peers()
elif choice == '7':
self._stop_node()
elif choice == '0':
break
else:
print("\n❌ Opción inválida\n")
def _show_node_info(self):
"""Muestra información del nodo"""
print("\n" + "="*60)
print("INFORMACIÓN DEL NODO P2P")
print("="*60)
info = self.p2p_node.get_network_info()
print(f"\nID del Nodo: {info['node_id']}")
print(f"Host: {info['host']}")
print(f"Puerto: {info['port']}")
print(f"Peers Conectados: {info['peers_count']}")
print(f"Uptime: {info['uptime']}")
print(f"\nBlockchain:")
print(f" Altura: {info['blockchain_height']} bloques")
print(f"\nEstadísticas:")
print(f" Bloques recibidos: {info['blocks_received']}")
print(f" Bloques enviados: {info['blocks_sent']}")
print(f" Transacciones recibidas: {info['transactions_received']}")
print(f" Transacciones enviadas: {info['transactions_sent']}")
print("="*60)
input("\nPresiona Enter para continuar...")
def _list_peers(self):
"""Lista los peers conectados"""
print("\n" + "="*60)
print("PEERS CONECTADOS")
print("="*60)
if not self.p2p_node.peers:
print("\nNo hay peers conectados")
else:
print(f"\nTotal: {len(self.p2p_node.peers)} peers\n")
for i, (host, port) in enumerate(self.p2p_node.peers, 1):
print(f"{i}. {host}:{port}")
print("="*60)
input("\nPresiona Enter para continuar...")
def _add_peer(self):
"""Agrega un peer"""
print("\n📡 AGREGAR PEER")
print("="*60)
host = input("Host/IP del peer: ").strip()
port = input("Puerto del peer: ").strip()
if not host or not port:
print("❌ Host y puerto son requeridos\n")
input("Presiona Enter para continuar...")
return
try:
port = int(port)
print(f"\n🔄 Conectando con {host}:{port}...")
success, msg = self.p2p_node.add_peer(host, port)
if success:
print(f"✅ {msg}")
print(f" Total peers: {len(self.p2p_node.peers)}")
else:
print(f"❌ {msg}")
except ValueError:
print("❌ Puerto inválido")
except Exception as e:
print(f"❌ Error: {e}")
print("="*60)
input("\nPresiona Enter para continuar...")
def _remove_peer(self):
"""Elimina un peer"""
if not self.p2p_node.peers:
print("\n❌ No hay peers conectados\n")
input("Presiona Enter para continuar...")
return
print("\n❌ ELIMINAR PEER")
print("="*60)
print("\nPeers conectados:")
peers_list = list(self.p2p_node.peers)
for i, (host, port) in enumerate(peers_list, 1):
print(f"{i}. {host}:{port}")
choice = input("\nNúmero de peer a eliminar (0 para cancelar): ").strip()
try:
choice = int(choice)
if choice == 0:
return
if 1 <= choice <= len(peers_list):
host, port = peers_list[choice - 1]
success, msg = self.p2p_node.remove_peer(host, port)
if success:
print(f"\n✅ {msg}")
else:
print(f"\n❌ {msg}")
else:
print("\n❌ Número inválido")
except ValueError:
print("\n❌ Entrada inválida")
print("="*60)
input("\nPresiona Enter para continuar...")
def _sync_network(self):
"""Sincroniza con la red"""
if not self.p2p_node.peers:
print("\n❌ No hay peers conectados para sincronizar\n")
input("Presiona Enter para continuar...")
return
print("\n🔄 SINCRONIZAR CON RED")
print("="*60)
print(f"\nSincronizando con {len(self.p2p_node.peers)} peers...")
self.p2p_node.sync_with_network()
print(f"\n✅ Sincronización completada")
print(f" Altura blockchain: {len(self.blockchain.chain)} bloques")
print("="*60)
input("\nPresiona Enter para continuar...")
def _discover_peers(self):
"""Descubre nuevos peers"""
print("\n🔍 DESCUBRIR PEERS")
print("="*60)
print("\nIngresa nodos semilla (host:puerto), uno por línea")
print("Deja vacío para terminar:")
seed_nodes = []
while True:
seed = input("> ").strip()
if not seed:
break
try:
host, port = seed.split(':')
seed_nodes.append((host, int(port)))
except:
print("❌ Formato inválido. Usa: host:puerto")
if not seed_nodes:
print("\n❌ No se ingresaron nodos semilla")
input("Presiona Enter para continuar...")
return
print(f"\n🔄 Descubriendo peers a través de {len(seed_nodes)} nodos semilla...")
discovered = self.p2p_node.discover_peers(seed_nodes)
print(f"\n✅ Descubrimiento completado")
print(f" Peers descubiertos: {discovered}")
print(f" Total peers: {len(self.p2p_node.peers)}")
print("="*60)
input("\nPresiona Enter para continuar...")
def _stop_node(self):
"""Detiene el nodo P2P"""
confirm = input("\n¿Detener el nodo P2P? (S/n): ").strip().lower()
if confirm != 'n':
self.p2p_node.stop()
self.p2p_node = None
print("\n🛑 Nodo P2P detenido\n")
input("Presiona Enter para continuar...")
def _create_timelock(self):
"""Crea un contrato timelock"""
if not self.wallet:
print("\n❌ Primero debes cargar una wallet\n")
input("Presiona Enter para continuar...")
return
print("\n📜 CREAR CONTRATO TIMELOCK")
print("="*60)
try:
unlock_block = int(input("Número de bloque para desbloquear: ").strip())
amount = float(input("Cantidad de CLC: ").strip())
recipient = input("Dirección del destinatario: ").strip()
contract = self.contract_manager.create_timelock(
creator=self.wallet.get_address(),
unlock_block=unlock_block,
amount=amount,
recipient=recipient
)
print(f"\n✅ Contrato Timelock creado")
print(f" ID: {contract.contract_id}")
print(f" Se desbloqueará en bloque: {unlock_block}")
print(f" Cantidad: {amount} CLC")
print(f" Destinatario: {recipient[:20]}...")
except ValueError:
print("❌ Valor inválido\n")
except Exception as e:
print(f"❌ Error: {e}\n")
print("="*60)
input("\nPresiona Enter para continuar...")
def _create_multisig(self):
"""Crea un contrato multisig"""
if not self.wallet:
print("\n❌ Primero debes cargar una wallet\n")
input("Presiona Enter para continuar...")
return
print("\n📜 CREAR CONTRATO MULTISIG")
print("="*60)
try:
required_sigs = int(input("Firmas requeridas: ").strip())
num_signers = int(input("Número total de firmantes: ").strip())
signers = []
print("\nIngresa las direcciones de los firmantes:")
for i in range(num_signers):
signer = input(f" Firmante {i+1}: ").strip()
signers.append(signer)
amount = float(input("\nCantidad de CLC: ").strip())
recipient = input("Dirección del destinatario: ").strip()
contract = self.contract_manager.create_multisig(
creator=self.wallet.get_address(),
required_sigs=required_sigs,
signers=signers,
amount=amount,
recipient=recipient
)
print(f"\n✅ Contrato Multisig creado")
print(f" ID: {contract.contract_id}")
print(f" Requiere: {required_sigs} de {num_signers} firmas")
print(f" Cantidad: {amount} CLC")
except ValueError:
print("❌ Valor inválido\n")
except Exception as e:
print(f"❌ Error: {e}\n")
print("="*60)
input("\nPresiona Enter para continuar...")
def _create_escrow(self):
"""Crea un contrato escrow"""
if not self.wallet:
print("\n❌ Primero debes cargar una wallet\n")
input("Presiona Enter para continuar...")
return
print("\n📜 CREAR CONTRATO ESCROW")
print("="*60)
try:
buyer = input("Dirección del comprador: ").strip()
seller = input("Dirección del vendedor: ").strip()
arbiter = input("Dirección del árbitro: ").strip()
amount = float(input("Cantidad de CLC: ").strip())
contract = self.contract_manager.create_escrow(
creator=self.wallet.get_address(),
buyer=buyer,
seller=seller,
arbiter=arbiter,
amount=amount
)
print(f"\n✅ Contrato Escrow creado")
print(f" ID: {contract.contract_id}")
print(f" Comprador: {buyer[:20]}...")
print(f" Vendedor: {seller[:20]}...")
print(f" Árbitro: {arbiter[:20]}...")
print(f" Cantidad: {amount} CLC")
except ValueError:
print("❌ Valor inválido\n")
except Exception as e:
print(f"❌ Error: {e}\n")
print("="*60)
input("\nPresiona Enter para continuar...")
def _list_contracts(self):
"""Lista todos los contratos"""
print("\n📜 CONTRATOS")
print("="*60)
contracts = self.contract_manager.list_contracts()
if not contracts:
print("\nNo hay contratos creados")
else:
for contract in contracts:
info = contract.get_info()
status = "✅ Ejecutado" if contract.executed else "⏳ Pendiente"
print(f"\n{contract.contract_id}: {info['type']}")
print(f" Estado: {status}")
if contract.contract_type == ContractType.TIMELOCK:
print(f" Desbloqueo: Bloque {info['unlock_block']}")
print(f" Cantidad: {info['amount']} CLC")
elif contract.contract_type == ContractType.MULTISIG:
print(f" Firmas: {info['status']}")
print(f" Cantidad: {info['amount']} CLC")
elif contract.contract_type == ContractType.ESCROW:
print(f" Estado: {info['status']}")
print(f" Cantidad: {info['amount']} CLC")
print("="*60)
input("\nPresiona Enter para continuar...")
def _view_contract(self):
"""Ver detalles de un contrato"""
contract_id = input("\nID del contrato: ").strip()
contract = self.contract_manager.get_contract(contract_id)
if not contract:
print(f"❌ Contrato {contract_id} no encontrado\n")
input("Presiona Enter para continuar...")
return
print("\n" + "="*60)
print(f"CONTRATO {contract_id}")
print("="*60)
info = contract.get_info()
print(f"\nTipo: {info['type']}")
print(f"Creador: {contract.creator[:20]}...")
print(f"Estado: {'✅ Ejecutado' if contract.executed else '⏳ Pendiente'}")
for key, value in info.items():
if key != 'type':
print(f"{key}: {value}")
if contract.execution_result:
print(f"\nResultado de ejecución:")
print(f" Éxito: {contract.execution_result['success']}")
print(f" Gas usado: {contract.execution_result.get('gas_used', 'N/A')}")
print("="*60)
input("\nPresiona Enter para continuar...")
def _execute_contract(self):
"""Ejecuta un contrato"""
contract_id = input("\nID del contrato: ").strip()
contract = self.contract_manager.get_contract(contract_id)
if not contract:
print(f"❌ Contrato {contract_id} no encontrado\n")
input("Presiona Enter para continuar...")
return
if contract.executed:
print(f"❌ El contrato ya fue ejecutado\n")
input("Presiona Enter para continuar...")
return
print(f"\n⚙️ Ejecutando contrato {contract_id}...")
context = {'block_height': len(self.blockchain.chain)}
success, msg = self.contract_manager.execute_contract(contract_id, context)
if success:
print(f"✅ {msg}")
if contract.execution_result:
print(f" Gas usado: {contract.execution_result['gas_used']}")
else:
print(f"❌ {msg}")
input("\nPresiona Enter para continuar...")
def _sign_multisig(self):
"""Firma un contrato multisig"""
if not self.wallet:
print("\n❌ Primero debes cargar una wallet\n")
input("Presiona Enter para continuar...")
return
contract_id = input("\nID del contrato Multisig: ").strip()
contract = self.contract_manager.get_contract(contract_id)
if not contract:
print(f"❌ Contrato {contract_id} no encontrado\n")
input("Presiona Enter para continuar...")
return
if contract.contract_type != ContractType.MULTISIG:
print(f"❌ El contrato no es tipo Multisig\n")
input("Presiona Enter para continuar...")
return
success = contract.add_signature(self.wallet.get_address())
if success:
print(f"✅ Firma agregada exitosamente")
info = contract.get_info()
print(f" Estado: {info['status']}")
self.contract_manager.save_contracts()
else:
print(f"❌ No puedes firmar este contrato")
input("\nPresiona Enter para continuar...")
def _decide_escrow(self):
"""Decide un contrato escrow"""
if not self.wallet:
print("\n❌ Primero debes cargar una wallet\n")
input("Presiona Enter para continuar...")
return
contract_id = input("\nID del contrato Escrow: ").strip()
contract = self.contract_manager.get_contract(contract_id)
if not contract:
print(f"❌ Contrato {contract_id} no encontrado\n")
input("Presiona Enter para continuar...")
return
if contract.contract_type != ContractType.ESCROW:
print(f"❌ El contrato no es tipo Escrow\n")
input("Presiona Enter para continuar...")
return
decision = input("\n¿Aprobar transacción? (S/n): ").strip().lower()
approve = decision != 'n'
success, msg = contract.make_decision(self.wallet.get_address(), approve)
if success:
print(f"✅ {msg}")
self.contract_manager.save_contracts()
else:
print(f"❌ {msg}")
input("\nPresiona Enter para continuar...")
def _show_difficulty_info(self):
"""Muestra información sobre la dificultad"""
from blockchain.difficulty import DifficultyAdjustment
info = DifficultyAdjustment.get_adjustment_info(self.blockchain)
print("\n" + "="*60)
print("⚙️ INFORMACIÓN DE DIFICULTAD")
print("="*60)
print(f"\n📊 Estado Actual:")
print(f" Dificultad: {info['current_difficulty']} ceros")
print(f" Tiempo promedio por bloque: {info['current_avg_time']:.2f}s")
print(f" Tiempo objetivo: {info['target_block_time']}s")
if info['current_avg_time'] > 0:
if info['current_avg_time'] < info['target_block_time'] * 0.5:
status = "⚡ Muy rápido"
elif info['current_avg_time'] < info['target_block_time'] * 0.75:
status = "🔥 Rápido"
elif info['current_avg_time'] > info['target_block_time'] * 2:
status = "🐌 Muy lento"
elif info['current_avg_time'] > info['target_block_time'] * 1.5:
status = "🕐 Lento"
else: