|
8 | 8 | "fmt" |
9 | 9 | "math/big" |
10 | 10 | "net/http" |
| 11 | + "runtime" |
11 | 12 | "strings" |
12 | 13 | "sync" |
13 | 14 | "time" |
@@ -135,28 +136,59 @@ func (c *EngineClient) GetTxs(ctx context.Context) ([][]byte, error) { |
135 | 136 | return nil, fmt.Errorf("failed to get tx pool content: %w", err) |
136 | 137 | } |
137 | 138 |
|
138 | | - var txs [][]byte |
139 | | - |
140 | | - // add pending txs |
| 139 | + // Step 1: Flatten all txs into a slice |
| 140 | + var allTxs []*types.Transaction |
141 | 141 | for _, accountTxs := range result.Pending { |
142 | 142 | for _, tx := range accountTxs { |
143 | | - txBytes, err := tx.MarshalBinary() |
144 | | - if err != nil { |
145 | | - return nil, fmt.Errorf("failed to marshal transaction: %w", err) |
146 | | - } |
147 | | - txs = append(txs, txBytes) |
| 143 | + allTxs = append(allTxs, tx) |
148 | 144 | } |
149 | 145 | } |
150 | | - |
151 | | - // add queued txs |
152 | 146 | for _, accountTxs := range result.Queued { |
153 | 147 | for _, tx := range accountTxs { |
| 148 | + allTxs = append(allTxs, tx) |
| 149 | + } |
| 150 | + } |
| 151 | + |
| 152 | + txs := make([][]byte, len(allTxs)) |
| 153 | + numWorkers := runtime.NumCPU() |
| 154 | + jobs := make(chan int, len(allTxs)) |
| 155 | + errCh := make(chan error, 1) |
| 156 | + var wg sync.WaitGroup |
| 157 | + |
| 158 | + // Worker function |
| 159 | + worker := func() { |
| 160 | + for i := range jobs { |
| 161 | + tx := allTxs[i] |
154 | 162 | txBytes, err := tx.MarshalBinary() |
155 | 163 | if err != nil { |
156 | | - return nil, fmt.Errorf("failed to marshal transaction: %w", err) |
| 164 | + // Only send the first error |
| 165 | + select { |
| 166 | + case errCh <- err: |
| 167 | + default: |
| 168 | + } |
| 169 | + continue |
157 | 170 | } |
158 | | - txs = append(txs, txBytes) |
| 171 | + txs[i] = txBytes |
159 | 172 | } |
| 173 | + wg.Done() |
| 174 | + } |
| 175 | + |
| 176 | + // Start workers |
| 177 | + wg.Add(numWorkers) |
| 178 | + for w := 0; w < numWorkers; w++ { |
| 179 | + go worker() |
| 180 | + } |
| 181 | + |
| 182 | + // Send jobs |
| 183 | + for i := range allTxs { |
| 184 | + jobs <- i |
| 185 | + } |
| 186 | + close(jobs) |
| 187 | + |
| 188 | + wg.Wait() |
| 189 | + close(errCh) |
| 190 | + if err, ok := <-errCh; ok { |
| 191 | + return nil, fmt.Errorf("failed to marshal transaction: %w", err) |
160 | 192 | } |
161 | 193 | return txs, nil |
162 | 194 | } |
|
0 commit comments