| 1041 | } |
| 1042 | |
| 1043 | CWalletTx* CWallet::AddToWallet(CTransactionRef tx, const TxState& state, const UpdateWalletTxFn& update_wtx, bool rescanning_old_block) |
| 1044 | { |
| 1045 | LOCK(cs_wallet); |
| 1046 | |
| 1047 | WalletBatch batch(GetDatabase()); |
| 1048 | |
| 1049 | Txid hash = tx->GetHash(); |
| 1050 | |
| 1051 | if (IsWalletFlagSet(WALLET_FLAG_AVOID_REUSE)) { |
| 1052 | // Mark used destinations |
| 1053 | std::set<CTxDestination> tx_destinations; |
| 1054 | |
| 1055 | for (const CTxIn& txin : tx->vin) { |
| 1056 | const COutPoint& op = txin.prevout; |
| 1057 | SetSpentKeyState(batch, op.hash, op.n, true, tx_destinations); |
| 1058 | } |
| 1059 | |
| 1060 | MarkDestinationsDirty(tx_destinations); |
| 1061 | } |
| 1062 | |
| 1063 | // Inserts only if not already there, returns tx inserted or tx found |
| 1064 | auto ret = mapWallet.emplace(std::piecewise_construct, std::forward_as_tuple(hash), std::forward_as_tuple(tx, state)); |
| 1065 | CWalletTx& wtx = (*ret.first).second; |
| 1066 | bool fInsertedNew = ret.second; |
| 1067 | bool fUpdated = update_wtx && update_wtx(wtx, fInsertedNew); |
| 1068 | if (fInsertedNew) { |
| 1069 | wtx.nTimeReceived = GetTime(); |
| 1070 | wtx.nOrderPos = IncOrderPosNext(&batch); |
| 1071 | wtx.m_it_wtxOrdered = wtxOrdered.insert(std::make_pair(wtx.nOrderPos, &wtx)); |
| 1072 | wtx.nTimeSmart = ComputeTimeSmart(wtx, rescanning_old_block); |
| 1073 | AddToSpends(wtx); |
| 1074 | |
| 1075 | // Update birth time when tx time is older than it. |
| 1076 | MaybeUpdateBirthTime(wtx.GetTxTime()); |
| 1077 | } |
| 1078 | |
| 1079 | if (!fInsertedNew) |
| 1080 | { |
| 1081 | if (state.index() != wtx.m_state.index()) { |
| 1082 | wtx.m_state = state; |
| 1083 | fUpdated = true; |
| 1084 | } else { |
| 1085 | assert(TxStateSerializedIndex(wtx.m_state) == TxStateSerializedIndex(state)); |
| 1086 | assert(TxStateSerializedBlockHash(wtx.m_state) == TxStateSerializedBlockHash(state)); |
| 1087 | } |
| 1088 | // If we have a witness-stripped version of this transaction, and we |
| 1089 | // see a new version with a witness, then we must be upgrading a pre-segwit |
| 1090 | // wallet. Store the new version of the transaction with the witness, |
| 1091 | // as the stripped-version must be invalid. |
| 1092 | // TODO: Store all versions of the transaction, instead of just one. |
| 1093 | if (tx->HasWitness() && !wtx.tx->HasWitness()) { |
| 1094 | wtx.SetTx(tx); |
| 1095 | fUpdated = true; |
| 1096 | } |
| 1097 | } |
| 1098 | |
| 1099 | // Mark inactive coinbase transactions and their descendants as abandoned |
| 1100 | if (wtx.IsCoinBase() && wtx.isInactive()) { |