Skip to content
This repository has been archived by the owner on Dec 11, 2019. It is now read-only.

Removes transition btc->bat code #13039

Merged
merged 2 commits into from
Feb 21, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
184 changes: 17 additions & 167 deletions app/browser/api/ledger.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ const appActions = require('../../../js/actions/appActions')
// State
const ledgerState = require('../../common/state/ledgerState')
const pageDataState = require('../../common/state/pageDataState')
const migrationState = require('../../common/state/migrationState')
const updateState = require('../../common/state/updateState')

// Constants
Expand Down Expand Up @@ -85,7 +84,6 @@ let verifiedTimeoutId = false
let v2RulesetDB
const v2RulesetPath = 'ledger-rulesV2.leveldb'
const statePath = 'ledger-state.json'
const newClientPath = 'ledger-newstate.json'

// Definitions
const clientOptions = {
Expand Down Expand Up @@ -1223,8 +1221,6 @@ const checkPromotions = () => {

const enable = (state, paymentsEnabled) => {
if (paymentsEnabled) {
state = checkBtcBatMigrated(state, paymentsEnabled)

if (!getSetting(settings.PAYMENTS_NOTIFICATION_TRY_PAYMENTS_DISMISSED)) {
appActions.changeSetting(settings.PAYMENTS_NOTIFICATION_TRY_PAYMENTS_DISMISSED, true)
}
Expand Down Expand Up @@ -1505,7 +1501,7 @@ const getStateInfo = (state, parsedData) => {
const info = parsedData.paymentInfo
const then = new Date().getTime() - ledgerUtil.milliseconds.year

if (!parsedData.properties.wallet) {
if (!parsedData.properties || !parsedData.properties.wallet) {
return state
}

Expand Down Expand Up @@ -1915,19 +1911,6 @@ const onCallback = (state, result, delayTime) => {
// persist the new ledger state
muonWriter(statePath, regularResults)

// delete the temp file used during transition (if it still exists)
if (client && client.options && client.options.version === 'v2') {
const fs = require('fs')
fs.access(pathName(newClientPath), fs.FF_OK, (err) => {
if (err) {
return
}
fs.unlink(pathName(newClientPath), (err) => {
if (err) console.error('unlink error: ' + err.toString())
})
})
}

run(state, delayTime)

return state
Expand Down Expand Up @@ -2019,7 +2002,6 @@ const initialize = (state, paymentsEnabled) => {

if (!paymentsEnabled) {
client = null
newClient = false
return ledgerState.resetInfo(state, true)
}

Expand Down Expand Up @@ -2075,6 +2057,22 @@ const getContributionAmount = (state) => {
}

const onInitRead = (state, parsedData) => {
const isBTC = parsedData &&
parsedData.properties &&
parsedData.properties.wallet &&
parsedData.properties.wallet.keychains

if (isBTC) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should add verbose logging here- something like:
Bitcoin wallet detected; backing up to "ledger-state-btc.json" and creating new BAT wallet

const fs = require('fs')
fs.renameSync(pathName(statePath), pathName('ledger-state-btc.json'))
state = ledgerState.resetInfo(state)
clientprep()
client = ledgerClient(null, underscore.extend({roundtrip: roundtrip}, clientOptions), null)
parsedData = client.state
getPaymentInfo(state)
muonWriter(statePath, parsedData)
}

if (Array.isArray(parsedData.transactions)) {
parsedData.transactions.sort((transaction1, transaction2) => {
return transaction1.submissionStamp - transaction2.submissionStamp
Expand Down Expand Up @@ -2393,147 +2391,6 @@ const deleteSynopsis = () => {
synopsis.publishers = {}
}

// fix for incorrectly persisted state (see #11585)
const yoDawg = (stateState) => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

RIP the yoDawg bug fix 💯
cc: @evq

while (stateState.hasOwnProperty('state') && stateState.state.persona) {
stateState = stateState.state
}
return stateState
}

const checkBtcBatMigrated = (state, paymentsEnabled) => {
if (!paymentsEnabled) {
return state
}

// One time conversion of wallet
const isNewInstall = migrationState.isNewInstall(state)
const hasUpgradedWallet = migrationState.hasUpgradedWallet(state)
if (!isNewInstall && !hasUpgradedWallet) {
state = migrationState.setTransitionStatus(state, true)
module.exports.transitionWalletToBat()
} else {
state = migrationState.setTransitionStatus(state, false)
}

return state
}

let newClient = null
const getNewClient = () => {
return newClient
}

let busyRetryCount = 0

const transitionWalletToBat = () => {
let newPaymentId, result

if (newClient === true) return
clientprep()

if (!client) {
console.log('Client is not initialized, will try again')
return
}

// only attempt this transition if the wallet is v1
if (client.options && client.options.version !== 'v1') {
// older versions incorrectly marked this for transition
// this will clean them up (no more bouncy ball)
appActions.onBitcoinToBatTransitioned()
return
}

// Restore newClient from the file (if one exists)
if (!newClient) {
const fs = require('fs')
try {
fs.accessSync(pathName(newClientPath), fs.FF_OK)
fs.readFile(pathName(newClientPath), (error, data) => {
if (error) {
console.error(`ledger client: can't read ${newClientPath} to restore newClient`)
return
}
const parsedData = JSON.parse(data)
const state = yoDawg(parsedData)
newClient = ledgerClient(state.personaId,
underscore.extend(state.options, {roundtrip: module.exports.roundtrip}, clientOptions),
state)
transitionWalletToBat()
})
return
} catch (err) {}
}

// Create new client
if (!newClient) {
try {
newClient = ledgerClient(null, underscore.extend({roundtrip: module.exports.roundtrip}, clientOptions), null)
muonWriter(newClientPath, newClient.state)
} catch (ex) {
console.error('ledger client creation error(2): ', ex)
return
}
}

newPaymentId = newClient.getPaymentId()
if (!newPaymentId) {
newClient.sync((err, result, delayTime) => {
if (err) {
return console.error('ledger client error(3): ' + JSON.stringify(err, null, 2) + (err.stack ? ('\n' + err.stack) : ''))
}

if (typeof delayTime === 'undefined') delayTime = random.randomInt({ min: 1, max: 500 })

if (newClient) {
muonWriter(newClientPath, newClient.state)
}

setTimeout(() => transitionWalletToBat(), delayTime)
})
return
}

if (client.busyP()) {
if (++busyRetryCount > 3) {
console.log('ledger client is currently busy; transition will be retried on next launch')
return
}
const delayTime = random.randomInt({
min: ledgerUtil.milliseconds.minute,
max: 10 * ledgerUtil.milliseconds.minute
})
console.log('ledger client is currently busy; transition will be retried shortly (this was attempt ' + busyRetryCount + ')')
setTimeout(() => transitionWalletToBat(), delayTime)
return
}

appActions.onBitcoinToBatBeginTransition()

try {
client.transition(newPaymentId, (err, properties) => {
if (err || !newClient) {
console.error('ledger client transition error: ', err)
} else {
result = newClient.transitioned(properties)
client = newClient
newClient = true
// NOTE: onLedgerCallback will save latest client to disk as ledger-state.json
appActions.onLedgerCallback(result, random.randomInt({
min: ledgerUtil.milliseconds.minute,
max: 10 * ledgerUtil.milliseconds.minute
}))
appActions.onBitcoinToBatTransitioned()
ledgerNotifications.showBraveWalletUpdated()
getPublisherTimestamp()
}
})
} catch (ex) {
console.error('exception during ledger client transition: ', ex)
}
}

let currentMediaKey = null
const onMediaRequest = (state, xhr, type, tabId) => {
if (!xhr || type == null) {
Expand Down Expand Up @@ -2872,13 +2729,10 @@ const getMethods = () => {
migration,
onInitRead,
deleteSynopsis,
transitionWalletToBat,
getNewClient,
normalizePinned,
roundToTarget,
savePublisherData,
pruneSynopsis,
checkBtcBatMigrated,
onMediaRequest,
onMediaPublisher,
saveVisit,
Expand All @@ -2900,7 +2754,6 @@ const getMethods = () => {
privateMethods = {
enable,
addSiteVisit,
checkBtcBatMigrated,
clearVisitsByPublisher: function () {
visitsByPublisher = {}
},
Expand All @@ -2911,9 +2764,6 @@ const getMethods = () => {
setSynopsis: (data) => {
synopsis = data
},
resetNewClient: () => {
newClient = false
},
getClient: () => {
return client
},
Expand Down
53 changes: 1 addition & 52 deletions app/browser/api/ledgerNotifications.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ const settings = require('../../../js/constants/settings')

// State
const ledgerState = require('../../common/state/ledgerState')
const migrationState = require('../../common/state/migrationState')

// Actions
const appActions = require('../../../js/actions/appActions')
Expand All @@ -27,8 +26,7 @@ const text = {
paymentDone: undefined,
addFunds: locale.translation('addFundsNotification'),
tryPayments: locale.translation('notificationTryPayments'),
reconciliation: locale.translation('reconciliationNotification'),
walletConvertedToBat: locale.translation('walletConvertedToBat')
reconciliation: locale.translation('reconciliationNotification')
}

const pollingInterval = 15 * ledgerUtil.milliseconds.minute // 15 * minutes
Expand Down Expand Up @@ -76,28 +74,11 @@ const onLaunch = (state) => {
return state
}

const ledger = require('./ledger')
state = ledger.checkBtcBatMigrated(state, enabled)

if (hasFunds(state)) {
// Don't bother processing the rest, which are only
if (!getSetting(settings.PAYMENTS_NOTIFICATIONS)) {
return state
}

// Show one-time BAT conversion message:
// - if payments are enabled
// - user has a positive balance
// - this is an existing profile (new profiles will have firstRunTimestamp matching batMercuryTimestamp)
// - wallet has been transitioned
// - notification has not already been shown yet
// (see https://github.com/brave/browser-laptop/issues/11021)
const isNewInstall = migrationState.isNewInstall(state)
const hasUpgradedWallet = migrationState.hasUpgradedWallet(state)
const hasBeenNotified = migrationState.hasBeenNotified(state)
if (!isNewInstall && hasUpgradedWallet && !hasBeenNotified) {
module.exports.showBraveWalletUpdated()
}
}

return state
Expand Down Expand Up @@ -181,16 +162,6 @@ const onResponse = (message, buttonIndex, activeWindow) => {
appActions.changeSetting(settings.PAYMENTS_NOTIFICATION_TRY_PAYMENTS_DISMISSED, true)
break

case text.walletConvertedToBat:
if (buttonIndex === 0) {
// Open backup modal
appActions.createTabRequested({
url: 'about:preferences#payments?ledgerBackupOverlayVisible',
windowId: activeWindow.id
})
}
break

default:
return
}
Expand Down Expand Up @@ -324,27 +295,6 @@ const showPaymentDone = (transactionContributionFiat) => {
})
}

const showBraveWalletUpdated = () => {
appActions.onBitcoinToBatNotified()

appActions.showNotification({
position: 'global',
greeting: text.hello,
message: text.walletConvertedToBat,
// Learn More.
buttons: [
{text: locale.translation('walletConvertedBackup')},
{text: locale.translation('walletConvertedDismiss')}
],
options: {
style: 'greetingStyle',
persist: false,
advancedLink: 'https://brave.com/faq-payments/#brave-payments',
advancedText: locale.translation('walletConvertedLearnMore')
}
})
}

const onPromotionReceived = (state) => {
const promotion = ledgerState.getPromotionNotification(state)

Expand Down Expand Up @@ -410,7 +360,6 @@ const getMethods = () => {
showPaymentDone,
init,
onLaunch,
showBraveWalletUpdated,
onInterval,
onPromotionReceived,
removePromotionNotification,
Expand Down
Loading