|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "flag" |
| 6 | + "fmt" |
| 7 | + "go-backfill/config" |
| 8 | + "go-backfill/fetch" |
| 9 | + "go-backfill/process" |
| 10 | + "go-backfill/repository" |
| 11 | + "log" |
| 12 | + "strconv" |
| 13 | + "time" |
| 14 | + |
| 15 | + "github.com/jackc/pgx/v5" |
| 16 | +) |
| 17 | + |
| 18 | +const ( |
| 19 | + coinbaseBatchSize = 1000 |
| 20 | +) |
| 21 | + |
| 22 | +type CoinbaseData struct { |
| 23 | + ID int64 `json:"id"` |
| 24 | + Coinbase string `json:"coinbase"` |
| 25 | + ChainId int `json:"chainId"` |
| 26 | + CreationTime string `json:"creationTime"` |
| 27 | +} |
| 28 | + |
| 29 | +func createBatchCoinbase(conn *pgx.Conn, lastId int64, network string) (bool, int64, error) { |
| 30 | + startTime := time.Now() |
| 31 | + |
| 32 | + // Start transaction for writes |
| 33 | + tx, err := conn.Begin(context.Background()) |
| 34 | + if err != nil { |
| 35 | + return false, lastId, fmt.Errorf("failed to begin transaction: %v", err) |
| 36 | + } |
| 37 | + defer tx.Rollback(context.Background()) |
| 38 | + |
| 39 | + // Fetch blocks with coinbase data using cursor pagination |
| 40 | + query := ` |
| 41 | + SELECT id, coinbase, "chainId", "creationTime" |
| 42 | + FROM "Blocks" |
| 43 | + WHERE id > $1 |
| 44 | + ORDER BY id ASC |
| 45 | + LIMIT $2 |
| 46 | + ` |
| 47 | + |
| 48 | + rows, err := conn.Query(context.Background(), query, lastId, coinbaseBatchSize) |
| 49 | + if err != nil { |
| 50 | + return false, lastId, fmt.Errorf("failed to execute query: %v", err) |
| 51 | + } |
| 52 | + defer rows.Close() |
| 53 | + |
| 54 | + var blocks []CoinbaseData |
| 55 | + for rows.Next() { |
| 56 | + var block CoinbaseData |
| 57 | + if err := rows.Scan(&block.ID, &block.Coinbase, &block.ChainId, &block.CreationTime); err != nil { |
| 58 | + return false, lastId, fmt.Errorf("failed to scan row: %v", err) |
| 59 | + } |
| 60 | + blocks = append(blocks, block) |
| 61 | + } |
| 62 | + |
| 63 | + if len(blocks) == 0 { |
| 64 | + return false, lastId, nil |
| 65 | + } |
| 66 | + |
| 67 | + // Process each block's coinbase transaction |
| 68 | + var transactions []repository.TransactionAttributes |
| 69 | + var transactionIds []int64 |
| 70 | + for _, block := range blocks { |
| 71 | + creationTime, err := strconv.ParseInt(block.CreationTime, 10, 64) |
| 72 | + if err != nil { |
| 73 | + return false, lastId, fmt.Errorf("failed to parse creation time for block %d: %v", block.ID, err) |
| 74 | + } |
| 75 | + tx, err := process.ProcessCoinbaseTransaction(block.Coinbase, block.ID, creationTime, int64(block.ChainId)) |
| 76 | + if err != nil { |
| 77 | + return false, lastId, fmt.Errorf("failed to process coinbase for block %d: %v", block.ID, err) |
| 78 | + } |
| 79 | + transactions = append(transactions, tx) |
| 80 | + } |
| 81 | + |
| 82 | + // Save transactions to database |
| 83 | + if len(transactions) > 0 { |
| 84 | + ids, err := repository.SaveTransactions(tx, transactions, repository.TransactionAttributes{}) |
| 85 | + if err != nil { |
| 86 | + return false, lastId, fmt.Errorf("failed to save transactions: %v", err) |
| 87 | + } |
| 88 | + transactionIds = ids |
| 89 | + |
| 90 | + // Process and save events and transfers for each coinbase transaction |
| 91 | + for i, block := range blocks { |
| 92 | + transactionId := transactionIds[i] |
| 93 | + |
| 94 | + // Create a ProcessedPayload structure for the coinbase events |
| 95 | + processedPayload := fetch.ProcessedPayload{ |
| 96 | + Header: fetch.Header{ |
| 97 | + ChainId: block.ChainId, |
| 98 | + }, |
| 99 | + Coinbase: []byte(block.Coinbase), |
| 100 | + } |
| 101 | + |
| 102 | + // Prepare and save events |
| 103 | + events, err := process.PrepareEvents(network, processedPayload, []int64{transactionId}) |
| 104 | + if err != nil { |
| 105 | + return false, lastId, fmt.Errorf("failed to prepare events for block %d: %v", block.ID, err) |
| 106 | + } |
| 107 | + |
| 108 | + if err := repository.SaveEventsToDatabase(events, tx); err != nil { |
| 109 | + return false, lastId, fmt.Errorf("failed to save events for block %d: %v", block.ID, err) |
| 110 | + } |
| 111 | + |
| 112 | + // Prepare and save transfers |
| 113 | + transfers, err := process.PrepareTransfers(network, processedPayload, []int64{transactionId}) |
| 114 | + if err != nil { |
| 115 | + return false, lastId, fmt.Errorf("failed to prepare transfers for block %d: %v", block.ID, err) |
| 116 | + } |
| 117 | + |
| 118 | + if err := repository.SaveTransfersToDatabase(transfers, tx); err != nil { |
| 119 | + return false, lastId, fmt.Errorf("failed to save transfers for block %d: %v", block.ID, err) |
| 120 | + } |
| 121 | + } |
| 122 | + } |
| 123 | + |
| 124 | + if err := tx.Commit(context.Background()); err != nil { |
| 125 | + return false, lastId, fmt.Errorf("failed to commit transaction: %v", err) |
| 126 | + } |
| 127 | + |
| 128 | + elapsed := time.Since(startTime) |
| 129 | + log.Printf("Processed %d coinbase transactions, their events, and transfers. Batch time: %.2fs", len(transactions), elapsed.Seconds()) |
| 130 | + |
| 131 | + // Return the last processed ID as the new cursor |
| 132 | + lastProcessedId := blocks[len(blocks)-1].ID |
| 133 | + return len(blocks) == coinbaseBatchSize, lastProcessedId, nil |
| 134 | +} |
| 135 | + |
| 136 | +func main() { |
| 137 | + envFile := flag.String("env", ".env", "Path to the .env file") |
| 138 | + flag.Parse() |
| 139 | + |
| 140 | + config.InitEnv(*envFile) |
| 141 | + env := config.GetConfig() |
| 142 | + |
| 143 | + // Database connection |
| 144 | + connStr := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable", |
| 145 | + env.DbHost, env.DbPort, env.DbUser, env.DbPassword, env.DbName) |
| 146 | + |
| 147 | + conn, err := pgx.Connect(context.Background(), connStr) |
| 148 | + if err != nil { |
| 149 | + log.Fatalf("Failed to connect to database: %v", err) |
| 150 | + } |
| 151 | + defer conn.Close(context.Background()) |
| 152 | + |
| 153 | + log.Println("Connected to database") |
| 154 | + |
| 155 | + lastId := int64(0) |
| 156 | + hasMore := true |
| 157 | + totalBlocks := int64(104813544) |
| 158 | + processedBlocks := int64(0) |
| 159 | + |
| 160 | + for hasMore { |
| 161 | + var err error |
| 162 | + hasMore, lastId, err = createBatchCoinbase(conn, lastId, env.Network) |
| 163 | + if err != nil { |
| 164 | + log.Fatalf("Error during batch processing: %v", err) |
| 165 | + } |
| 166 | + processedBlocks += coinbaseBatchSize |
| 167 | + progress := float64(processedBlocks) / float64(totalBlocks) * 100 |
| 168 | + |
| 169 | + if hasMore { |
| 170 | + log.Printf("Progress: %.2f%% (%d/%d blocks processed)", progress, processedBlocks, totalBlocks) |
| 171 | + } else { |
| 172 | + log.Printf("Progress: 100.00%%") |
| 173 | + } |
| 174 | + |
| 175 | + time.Sleep(100 * time.Millisecond) |
| 176 | + } |
| 177 | + |
| 178 | + log.Println("Coinbase creation completed successfully") |
| 179 | +} |
0 commit comments